How to connect to a Mysql database with php april 3, 2016 42 Comments


Download 26 Kb.
Sana08.06.2020
Hajmi26 Kb.
#116239
Bog'liq
How to connect-WPS Office


How to connect to a MySQL database with PHP

April 3, 2016 42 Comments

This tutorial will require a mysql database and a web development environment using mysql, apache and php and a simple text editor.

The tutorial takes you through establishing a mysql connection using php on a web page, connecting to a mysql table and retrieving the results and displaying them back on the web page.

This tutorial uses the PHP MySQL commands:

mysqli_connect

mysqli_query

mysqli_fetch_array

mysqli_close

The Plan


make the connection and select the database

perform the query on the table

print out the data

close the connection

First Up – Connecting to a MySQL database

You need your MySQL server address (if the database is on the same server as the web server it will most likely be localhost or 127.0.0.1), username, password and database name. Create a filenamehere.php file and open and close the php code with tags before the html, you can put regular html after it. Open the file in a browser and you should see nothing apart from the title tag, if you see the error the username/password or database name may be wrong.

PHP will require that mysqli is enabled (it is on most PHP set ups).

//Step1


$db = mysqli_connect('localhost','username','password','database_name')

or die('Error connecting to MySQL server.');

?>









PHP connect to MySQL



PHP connect to MySQL



//Step2


$query = "SELECT * FROM table_name";

mysqli_query($db, $query) or die('Error querying database.');

?>

PHP connect to MySQL



//Step2


$query = "SELECT * FROM table_name";

mysqli_query($db, $query) or die('Error querying database.');

$result = mysqli_query($db, $query);

$row = mysqli_fetch_array($result);

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

echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'


';

}

?>



PHP connect to MySQL



//Step2


$query = "SELECT * FROM table_name";

mysqli_query($db, $query) or die('Error querying database.');

//Step3

$result = mysqli_query($db, $query);



$row = mysqli_fetch_array($result);

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

echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'
';

}

//Step 4



mysqli_close($db);

?>
Download 26 Kb.

Do'stlaringiz bilan baham:




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling