I have finally graduated from MS Access to MySQL. Unfortunately, I can’t even get a query right. Can someone please tell me what’s wrong? I keep getting the ‘invalid query’ message that I specified in the php.
<?php
@ $db = mysql_connect('localhost', 'root', 'root', 'newdatabase');
if (!$db) {
die ('Failed to connect to the database.');
}
$query = "SELECT first FROM demographics";
$result = mysql_query($query);
if (!$result) {
die('invalid query');
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['first'];
}
?>
Also, the book I am reading tells me to use:
new mysqli('localhost', 'root', 'root', 'newdatabase')
to connect as opposed to the
mysql_connect
I used in the above code. I haven’t been able to connect to the db with new mysqli. Does it matter which one I use?
The fourth parameter to
mysql_connect()is not the database name. It is a boolean specifying whether or not to establish an additional new connection or use an existing one. Most often, it is omitted. Usemysql_select_db()to choose the database. Since you have not selected a database in your code, your query is likely failing.Note I have removed the
@from themysql_connect()call.@suppresses errors, and was probably preventing you from seeing what was going wrong with your connection.When testing the success or failure of a query, don’t
die(). Instead echo outmysql_error()while developing your application. In production, you can replace theechoby writing toerror_log()instead.As for using MySQLi instead of the basic
mysql_*functions, MySQLi can be used in an object oriented fashion and also offers prepared statements, which can be both more efficient to use and more secure. As mentioned in comments above, PDO is often recommended as the most flexible API for interacting with an RDBMS from PHP.