03.5: Use PHP to connect to MySQL
In this lesson we will learn how to create a PHP MySQLi connection, run a basic SELECT statement, and fetch a row from the result. To keep things simple we will do this from the command line and not use Apache.
# * If we do not have data in the database already from the previous lesson, we will manually add it now. # * Login to DB. mysql -u fuser -p friendplace # * Create our record. INSERT INTO users (name, email, password) VALUES ("Jim Smith", "jim@fakemail.com", "12345"); INSERT INTO users (name, email, password) VALUES ("Jane Marsha", "jane@fakemail.com", "abcde"); # * Fetch our record to test that it works. SELECT user_id, name, email FROM users WHERE email = "jim@fakemail.com" AND password = "12345";
<?php # * MySQL info $dbhost = "localhost"; $dbuser = "fuser"; $dbpass = "12345"; $dbname = "friendplace"; # * ------------------------------------------------------------- # * Create connection $conn = new mysqli( $dbhost, $dbuser, $dbpass, $dbname ); # * Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } # * ------------------------------------------------------------- # * Create the mysql query $email = "jim@fakemail.com"; $password = "12345"; $sql = "SELECT user_id, name FROM users WHERE email = '$email' and password = '$password';"; $result = mysqli_query( $conn, $sql ) or die( mysql_error() ); if ($num_rows = mysqli_num_rows( $result ) == 0) { echo "No rows returned from query.\n"; exit(); } # * ------------------------------------------------------------- # * Read the data $row = mysqli_fetch_row( $result ); $user_id = $row[0]; $name = $row[1]; print "user_id: $user_id\n"; print "name: $name\n"; ?>