0% found this document useful (0 votes)
5 views

PHP MySQL Basics

The document provides a comprehensive overview of basic PHP MySQL commands for performing CRUD operations, including connecting to a database, inserting, retrieving, updating, and deleting data. It also explains the use of prepared statements and stored procedures for secure and efficient database interactions. Additionally, it covers data types and operators in PHP, summarizing their usage with examples.

Uploaded by

cavife3393
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

PHP MySQL Basics

The document provides a comprehensive overview of basic PHP MySQL commands for performing CRUD operations, including connecting to a database, inserting, retrieving, updating, and deleting data. It also explains the use of prepared statements and stored procedures for secure and efficient database interactions. Additionally, it covers data types and operators in PHP, summarizing their usage with examples.

Uploaded by

cavife3393
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PHP MySQL Basics

basic commands of php mysql

Here are some basic PHP MySQL commands that help you connect, insert, retrieve, update, and
delete data in a MySQL database using PHP:

🔗 1. Connect to MySQL Database


php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb"; // Replace with your database name

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

📥 2. Insert Data
php

<?php
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
?>

📤 3. Retrieve (Select) Data


php

<?php
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/22
}
?>

✏️ 4. Update Data
php

<?php
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";

if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
?>

❌ 5. Delete Data
php

<?php
$sql = "DELETE FROM users WHERE id=1";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
?>

🔚 6. Close Connection
php

<?php
mysqli_close($conn);
?>

Would you like me to generate a complete sample CRUD project using these commands?
Here are basic MySQL commands used in the terminal (command-line interface), especially helpful
when working directly with the MySQL server:

🔐 1. Login to MySQL
bash

mysql -u username -p

Example:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/22
bash

mysql -u root -p

Then enter your password.

📦 2. Show All Databases


sql

SHOW DATABASES;

🗃️ 3. Create a New Database


sql

CREATE DATABASE dbname;

Example:

sql

CREATE DATABASE school;

✅ 4. Use a Specific Database


sql

USE dbname;

Example:

sql

USE school;

📄 5. Show Tables in Current Database


sql

SHOW TABLES;

🧱 6. Create a Table

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/22
sql

CREATE TABLE tablename (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);

🧾 7. Show Table Structure


sql

DESCRIBE tablename;

or

sql

DESC tablename;

✏️ 8. Insert Data into Table


sql

INSERT INTO tablename (name, email) VALUES ('John Doe', '[email protected]');

🔍 9. View Data in Table


sql

SELECT * FROM tablename;

✏️ 10. Update Data in Table


sql

UPDATE tablename SET email='[email protected]' WHERE id=1;

❌ 11. Delete Data from Table


sql

DELETE FROM tablename WHERE id=1;

🗑️ 12. Drop Table


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/22
sql

DROP TABLE tablename;

🧨 13. Drop Database


sql

DROP DATABASE dbname;

🚪 14. Exit MySQL


sql

EXIT;

or

sql

QUIT;

Let me know if you want examples using a real table like students, or how to back up/restore a database
from the terminal.

explain crud operations in php in easiest language

Sure, Vamthu! Let's understand CRUD operations in PHP in the simplest language with examples.

🧠 What is CRUD?
CRUD stands for:

Operation Meaning
C Create (Insert data into database)
R Read (Display data from database)
U Update (Change data in database)

D Delete (Remove data from database)

Let’s go step-by-step with basic PHP + MySQLi code examples.

🔗 Step 1: Connect to Database


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/22
php

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

🟢 C - Create (Insert Data)


php

<?php
$name = "John";
$email = "[email protected]";

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";


if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
?>

🔵 R - Read (Show Data)


php

<?php
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {


echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
?>

🟡 U - Update (Edit Data)


php

<?php
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
?>

🔴 D - Delete (Remove Data)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/22
php

<?php
$sql = "DELETE FROM users WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
?>

🔚 Close Connection
php

<?php
mysqli_close($conn);
?>

✅ Summary in Simple Words:


Create = Add new data to table
Read = View data from table

Update = Change data in table

Delete = Remove data from table

Would you like a full CRUD webpage example using forms (HTML + PHP)?

explain read operation again

Sure, Vamthu! Let's explain the Read operation again in the easiest way with example and steps.

🔵 READ Operation (R in CRUD)


🧠 What does it do?
It fetches and displays data from the database table using PHP and MySQL.

👇 Step-by-Step Explanation:
✅ 1. Connect to Database

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/22
php

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

✅ 2. Write SQL SELECT Query


php

$sql = "SELECT * FROM users";

This query says:


👉 “Select all columns ( ) from the
* users table.”

✅ 3. Run the Query


php

$result = mysqli_query($conn, $sql);

✅ 4. Check if Any Data is Returned


php

if (mysqli_num_rows($result) > 0) {
// loop through data
}

✅ 5. Fetch and Display the Data


php

while ($row = mysqli_fetch_assoc($result)) {


echo "ID: " . $row["id"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
echo "Email: " . $row["email"] . "<br><hr>";
}

💡 Full Working Example


php

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/22
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// show each row one by one
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
echo "Email: " . $row["email"] . "<br><hr>";
}
} else {
echo "No data found.";
}

mysqli_close($conn);
?>

📌 Output Example:
makefile

ID: 1
Name: John
Email: [email protected]
----------------------------
ID: 2
Name: Alice
Email: [email protected]

Would you like to learn how to display this in an HTML table?

Uploaded image
explain in detail as an...

The image contains the heading:

"Prepared Statement and Stored Procedure Execution in PHP"

Let's explain both concepts in detail and in simple language.

✅ 1. What is a Prepared Statement?


🔹 Definition:
A prepared statement is a way to safely run SQL queries in PHP, especially when you are using user
input (like from forms). It helps prevent SQL injection attacks.

📌 Why Use It?


Safe: Avoids SQL injection.
Fast: If the same query runs many times, it's optimized.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/22
Clean: Separates query and data.

✏️ Example: Prepared Statement (Insert Data)


php

<?php
$conn = new mysqli("localhost", "root", "", "testdb");

// Step 1: Prepare SQL


$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");

// Step 2: Bind values (s = string, i = integer, etc.)


$stmt->bind_param("ss", $name, $email);

// Step 3: Set data and execute


$name = "John";
$email = "[email protected]";
$stmt->execute();

echo "Data inserted successfully";

$stmt->close();
$conn->close();
?>

🧠 bind_param Types:
Type Meaning

i Integer

d Double
s String

b Blob (binary)

✅ 2. What is a Stored Procedure?


🔹 Definition:
A stored procedure is a SQL function saved inside the MySQL database. You can call it from PHP to
run multiple SQL statements together.

📌 Why Use It?


Reusable and faster.
Complex logic inside MySQL.

Easy to manage logic and security.

✏️ Step 1: Create Stored Procedure in MySQL


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/22
sql

DELIMITER //
CREATE PROCEDURE GetUsers()
BEGIN
SELECT * FROM users;
END //
DELIMITER ;

✏️ Step 2: Call Stored Procedure in PHP


php

<?php
$conn = new mysqli("localhost", "root", "", "testdb");

$sql = "CALL GetUsers()";


$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {


echo "Name: " . $row["name"] . " | Email: " . $row["email"] . "<br>";
}

$conn->close();
?>

📚 Summary:
Feature Prepared Statement Stored Procedure

Stored in MySQL? ❌ No ✅ Yes


Use in PHP ✅ Yes (with prepare) ✅ Yes (with CALL)
Security ✅ Very Safe (prevents SQL injection) ✅ Safe when used properly
Speed (Repeated use) ✅ Faster for repeated queries ✅ Fast for complex, repeated logic
Would you like a full CRUD example using prepared statements or stored procedures next?

data types and operators in php

Sure, Vamthu! Here's a simple and clear explanation of Data Types and Operators in PHP, with
examples.

📦 DATA TYPES in PHP


PHP supports 8 main data types. They are grouped into:

🔹 1. Scalar Types (single value)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/22
Type Example
int $a = 10;
float $b = 10.5;

string $name = "Vamthu";


bool $isAdmin = true;

🔹 2. Compound Types
Type Example
array $arr = array(1, 2, 3);

object $obj = new MyClass();

🔹 3. Special Types
Type Example
NULL $x = NULL;
resource $file = fopen("test.txt", "r");

🧮 OPERATORS in PHP
PHP operators are used to perform operations on variables and values.

🔹 1. Arithmetic Operators
Used to do math.

Operator Meaning Example


+ Addition 3 + 2
- Subtraction 5 - 2

* Multiplication 4 * 2
/ Division 10 / 2
% Modulus (Remainder) 5 % 2

🔹 2. Assignment Operators
Used to assign values.

Operator Example Meaning


= $a = 10; Assign 10 to $a
+= $a += 5; $a = $a + 5

-= $a -= 5; $a = $a - 5
*= $a *= 2; $a = $a * 2

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/22
🔹 3. Comparison Operators
Used in conditions (like if).

Operator Meaning Example ($a = 5, $b = 10)

== Equal (value) $a == $b → false


=== Equal (value & type) $a === "5" → false
!= Not equal $a != $b → true

> Greater than $a > $b → false


< Less than $a < $b → true

🔹 4. Logical Operators
Used to combine conditions.

Operator Meaning Example

&& AND if ($a > 0 && $b > 0)


` `
! NOT if (!($a > 0))

🔹 5. String Operator
Used to join strings.

Operator Meaning Example


. Concatenation $a = "Hello" . " Vamthu";

🔹 6. Increment/Decrement
Operator Meaning Example
++ Increment by 1 $a++

-- Decrement by 1 $a--

🔹 7. Ternary Operator
Short if-else condition:

php

$result = ($age >= 18) ? "Adult" : "Minor";

✅ Summary Table:
Data Type Example
int 5, 100

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/22
Data Type Example
float 10.5, 3.14
string "Hello"

bool true, false


array [1, 2, 3]
object new MyClass()
NULL NULL

resource fopen()

Would you like short coding exercises to practice these?

selection and loop statement in php with example

Sure Vamthu! Here's a simple explanation of Selection (Conditional) and Loop Statements in PHP,
with easy examples.

✅ 1. SELECTION (Conditional) Statements in PHP


These are used to make decisions in PHP code.

🔸 if Statement

Runs code if condition is true.

php

$age = 18;

if ($age >= 18) {


echo "You are an adult.";
}

🔸 if...else Statement

Chooses between two options.

php

$marks = 45;

if ($marks >= 50) {


echo "Pass";
} else {
echo "Fail";
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/22
🔸 if...elseif...else

Checks multiple conditions.

php

$score = 80;

if ($score >= 90) {


echo "Grade A";
} elseif ($score >= 75) {
echo "Grade B";
} else {
echo "Grade C";
}

🔸 switch Statement

Good for multiple fixed choices.

php

$day = "Tuesday";

switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Tuesday":
echo "Second day";
break;
default:
echo "Other day";
}

🔁 2. LOOPING Statements in PHP


Loops are used to repeat a block of code.

🔸 while Loop

Repeats while condition is true.

php

$i = 1;

while ($i <= 5) {


echo "Number: $i<br>";
$i++;
}

🔸 do...while Loop

Runs at least once, then checks condition.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/22
php

$i = 1;

do {
echo "Count: $i<br>";
$i++;
} while ($i <= 3);

🔸 for Loop

Used when you know the number of repetitions.

php

for ($i = 1; $i <= 5; $i++) {


echo "Hello $i<br>";
}

🔸 foreach Loop

Used to loop through arrays.

php

$fruits = array("Apple", "Banana", "Mango");

foreach ($fruits as $fruit) {


echo "Fruit: $fruit<br>";
}

🧠 Summary
Type Statement Used For

Selection if, if-else, switch Making decisions


Loop while, do-while, for, foreach Repeating tasks

Would you like a small mini program using both selection and loops together?

array creation,accessing array elements and types of array in php

Absolutely Vamthu! Here's a simple explanation of arrays in PHP, including how to create, access
elements, and the types of arrays — with clear examples.

📦 What is an Array?
An array is a variable that can store multiple values in a single variable.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/22
✅ How to Create an Array in PHP?
php

// Using array() function


$fruits = array("Apple", "Banana", "Mango");

// Using short syntax (PHP 5.4+)


$colors = ["Red", "Green", "Blue"];

🔍 How to Access Array Elements?


You use index numbers (starting from 0) or keys.

php

echo $fruits[0]; // Output: Apple


echo $colors[2]; // Output: Blue

📚 Types of Arrays in PHP


1. Indexed Array

Uses numeric index (starts from 0).

php

$animals = ["Dog", "Cat", "Elephant"];


echo $animals[1]; // Output: Cat

2. Associative Array

Uses named keys instead of numbers.

php

$person = [
"name" => "Vamthu",
"age" => 20,
"city" => "Chennai"
];

echo $person["name"]; // Output: Vamthu


echo $person["city"]; // Output: Chennai

3. Multidimensional Array

An array inside another array.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/22
php

$students = [
["John", 18],
["Vamthu", 20],
["Sara", 19]
];

echo $students[1][0]; // Output: Vamthu


echo $students[2][1]; // Output: 19

🔁 Looping Through Arrays


Indexed Array with for

php

$fruits = ["Apple", "Banana", "Mango"];

for ($i = 0; $i < count($fruits); $i++) {


echo $fruits[$i] . "<br>";
}

Associative Array with foreach

php

$person = ["name" => "Vamthu", "age" => 20];

foreach ($person as $key => $value) {


echo "$key: $value<br>";
}

📌 Summary Table
Type Key Type Example Access
Indexed Array Number $arr[0]
Associative Array Named keys $arr["name"]

Multidimensional Arrays inside arrays $arr[1][0]

Would you like a small quiz or program to test your array skills?

when we have to write echo and when print in php

Great question, Vamthu! Let’s understand when to use echo and when to use print in PHP, with easy
explanation and examples.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/22
✅ 1. What is echo in PHP?
echo is used to display output.

It can output multiple values separated by commas.


It is slightly faster than print.

🔸 Example:
php

echo "Hello, World!";


echo "Name: ", " Vamthu"; // Multiple strings

✅ 2. What is print in PHP?


print also displays output.
It returns a value (1), so it can be used in expressions.

It can only output one value at a time.

🔸 Example:
php

print "Welcome to PHP!";

// Since print returns 1, we can use it in conditions


$check = print "Check done!"; // $check will be 1

⚖️ Differences Between echo and print


Feature echo print
Returns a value ❌ No ✅ Yes (returns 1)
Output multiple values ✅ Yes (comma separated) ❌ No
Speed ✅ Slightly faster ❌ Slightly slower
Syntax flexibility ✅ More flexible ❌ Less flexible
Usage in expressions ❌ Cannot be used ✅ Can be used
🟡 When to Use What?
Situation Use
Just showing output (text, HTML) echo (faster & shorter)
You need to return a value or use in logic print (because it returns 1)
Outputting multiple values echo (supports commas)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/22
✅ Best Practice
Use echo most of the time because it’s faster and more flexible.
Use print only when you need a return value (e.g., in expressions or conditional output).

💡 Example: Echo vs Print


php

echo "Name: ", " Vamthu", "<br>"; ✅


// multiple values

if (print "Hello World<br>") { // works in condition ✅


echo "Printed Successfully!";
}

Would you like a small program to try both echo and print together?

form processing in php

Sure, Vamthu! Let's understand form processing in PHP in the simplest way possible, step by step —
with example.

🧾 What is Form Processing?


Form processing means:

1. Creating a form (HTML)


2. Submitting the form (using POST or GET method)

3. Collecting and processing data in PHP

✅ Step-by-Step Example
📌 Step 1: Create an HTML Form
html

<!-- save this as form.html -->


<form action="process.php" method="post">
Name: <input type="text" name="username"><br><br>
Email: <input type="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>

action="process.php": Tells the form to send data to this PHP file.


method="post": Secure way to send data (hidden in URL).

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/22
📌 Step 2: Create PHP File to Process Form
php

<!-- save this as process.php -->


<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Get data from form


$name = $_POST['username'];
$email = $_POST['email'];

// Display the data


echo "Your Name: " . $name . "<br>";
echo "Your Email: " . $email;
}
?>

🧠 Key Points
Concept Description

$_POST Used to get data from form with method="post"


$_GET Used when form has method="get" (not secure)
action attribute Tells where to send the form data
method attribute Tells how to send the data (GET or POST)

🚫 Optional: Validate Empty Input


php

if (empty($name) || empty($email)) {
echo "Please fill all fields!";
} else {
echo "Welcome, $name!";
}

✅ Summary
Use HTML to create the form.
Use PHP to receive and process data.

Use $_POST or $_GET to access form data.


Always check $_SERVER["REQUEST_METHOD"] to ensure the form was submitted.

Would you like me to add:

Form validation?
Saving form data to a database?

Sending form data via email?


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/22
Let me know!

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/22

You might also like