Performing Query

PHP and MySQL
PHP and MySQL : Home
Introduction to MySQL
mysqli class
Creating Connection
Performing Query
Handling Results

Query
Data stored in databases is of no use unless we can perform queries on it, i.e. get the desired outcome out of that data. For example We have a database of people of india and we want to know how many people live in Delhi, So we will perform query to get all the people who live in Delhi. The abiliity to perfrom queries is what makes database so useful.

We can perform query using query function of mysqli class. If you want to go by procedural style use mysqli_query function.

<?php
$mysqli_object = new mysqli("localhost","","","db");
$sql = "CREATE TABLE tb(sr INT, name VARCHAR(50))";

// If the query runs successfully the value  
// inside if statement will be equivalent to TRUE

if($mysqli_object->query($sql)){
    echo "Table created";
}

else{
    echo $mysqli_object->error;
}

?>


Output 1
Table created

Output 2
Table 'tb' already exists

While running foor the first, tb was not in database so we got output 1. If we run this program, an error will be thrown shown in output 2.
$sql - (String) The query that we are executing
Instead of storing query in variable($sql) and passing it to query function we could have directly passed query string inside function like this : query("CREATE TABLE tb(sr INT, name VARCHAR(50))")

$mysqli_object->error - String that contains last error stored. You you are unable to recall it, refer to the mysqli class section and look in properties.
Perfroming Query (Procedurel Method)

<?php
$connect = mysqli_connect("localhost","","","db");
$sql = "CREATE TABLE tb(sr INT, name VARCHAR(50))";

if(mysqli_query($connect,$sql)){
    echo "Table created";
}
else{
    echo mysqli_error($connect);
}
// You might have noticed that we have to
// pass connection variable everytime

?>


Output
Table 'tb' already exists

Login to Track Your Progress