💭
php
Created @August 11, 2021 1:43 PM
Daily
Tags
1) To check request is post or not.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
....
2) connection to the database
$servername = "localhost";
$username = "root";
$password = "";
$database = "name_of_db";
$conn = mysqli_connect($servername, $username, $password, $database);
3) How to run query
$sql = "create DATABASE student"; mysqli_query($conn,
$sql);
4) function which show database errormysqli_error($conn);
5) Database queries:
php 1
// Create a database
$sql = "CREATE DATABASE dbHarry";
$result = mysqli_query($conn, $sql);
// Check for the database creation success
if($result){
echo "The db was created successfully!<br>";
}
else{
echo "The db was not created successfully because of this error ---> ". mysqli_error
($conn);
}
// Insert query
$sql = "INSERT INTO `phptrip` (`name`, `dest`) VALUES ('$name', '$destination')";
$result = mysqli_query($conn, $sql);
// Add a new trip to the Trip table in the database
if($result){
echo "The record has been inserted successfully successfully!<br>";
}
else{
echo "The record was not inserted successfully because of this error ---> ". mysqli_er
ror($conn);
}
6) To see how much records inserted in database.
// Find the number of records returned
$num = mysqli_num_rows($result);
echo $num;
echo " records found in the DataBase<br>";
output: 6 records found in the Database
// We can fetch in a better way using the while loop
while($row = mysqli_fetch_assoc($result)){
php 2
// echo var_dump($row);
echo $row['sno'] . ". Hello ". $row['name'] ." Welcome to ". $row['dest'];
echo "<br>";
}
7) Updating data:
$sql = "update `login_info` set `name` = 'piyu' where `name` = 'priyanka'";
$result = mysqli_query($conn, $sql);
echo var_dump($result);
if($result){
echo "<br>record updated successfully<br>";
}
else{
echo "record not updated successfully". mysqli_error($conn);
}
$no_of_rows_affected = mysqli_affected_rows($conn);
echo $no_of_rows_affected. " rows are affected.";
8) LIMIT is use to limit the data, syntax :
$sql = "DELETE FROM `phptrip` WHERE `dest` = 'Russia' LIMIT 13";
$result = mysqli_query($conn, $sql);
It will delete first 13 data from table whose dest is Russia.
php 3