Retrieving Specific Data in MySQL/PHP PHP Script

Retrieving Specific Data in MySQL/PHP PHP Script

This tutorial is on how to retrieve specific data from a database through PHP and MySQL/MySQLi.

In my latest tutorials I have shown how to retrieve all rows from a database table, how to insert data, and how to validate data. Now I will show you how to retrieve specific data through slightly more advanced queries.

First you will obviously need a database with table. My database is named ‘fln’ and table is named ‘test’. It has two columns;
id, 5 length, primary key, auto increment, integer
score, 255 length, varchar

You can download the entire .sql file to import from the bottom of this tutorial article page. It is already populated with data so I will not run over that set, if you need to insert data, refer to one of my previous tutorials which can be found on my profile’s tacking page.

First we must make the PHP connection, like so…


       <?php           $con = mysqli_connect('localhost', 'root', '', 'fln'); //server, username, password, database name     ?>



What Data?
Next we must decide what data we want to have returned to us. Since my table only really consists of scores, I am first going to retrieve all scores between 100 and 1000.

Query Method:
We could do this through a MySQLi query, like so…


       $q = mysqli_query($con, "SELECT * FROM `test` WHERE `score`>'99' AND `score`<'1001'");     while ($row = mysqli_fetch_array($q)) {           echo 'Found query result; ' . $row['score'] . '<br/>';     }



PHP Method:
Or, we could retrieve all the rows and filter them through PHP, like so…


       $q = mysqli_query($con, "SELECT * FROM `test`");     $scores = array();     while ($row = mysqli_fetch_array($q)) {           if ($row['score'] > 99 && $row['score'] < 1001)                 array_push($scores, $row['score']);     }     foreach ($scores as $key => $value) {           echo $value . '<br/>';     }



So now we have an array of the correct score results. – We also output each one through a simple foreach loop.





Learn How to install Retrieving Specific Data in MySQL/PHP PHP Script?

Leave a Reply

Your email address will not be published. Required fields are marked *