PHP + MySQL query -> What's wrong with this SQL (short) - php

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. Use mysql_select_db() to choose the database. Since you have not selected a database in your code, your query is likely failing.
$db = mysql_connect('localhost', 'root', 'root');
if (!$db) echo mysql_error();
else mysql_select_db("database");
Note I have removed the # from the mysql_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 out mysql_error() while developing your application. In production, you can replace the echo by writing to error_log() instead.
if (!$result) {
echo mysql_error();
}
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.

Related

How can I make this function work with php 7.2? [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 4 years ago.
I have this piece of code that works fine with php5.6 but it breaks with php7.2.
I had three errors and I was able to fix two, I believe :)
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Could not connect !');
exit();
}
else{
mysql_set_charset('utf8',$link);
mysql_select_db($database, $link) or die('Could not select database.');
}
this is what I have so far
$link = mysqli_connect($hostname, $username, $password);
if (!$link) {
die('Could not connect !');
exit();
}
else{
mysqli_set_charset('utf8',$link);
mysqli_select_db($database, $link) or die('Could not select database.');
}
Fatal error with mysql_select_db()
How can I make this function work with php 7.2? any help will be greatly appreciated, thank you in advance!!
The mysqli_* API requires that the database connection come first (unlike the old and deprecated mysql_* API which is no longer supported in PHP 7.2):
$link = mysqli_connect($hostname, $username, $password);
if (!$link) {
die('Could not connect !');
exit();
}
else{
mysqli_set_charset($link, 'utf8');
mysqli_select_db($link, $database) or die('Could not select database.');
}
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqli.select-db.php
http://php.net/manual/en/mysqli.set-charset.php
Make sure that you did in fact assign something to the $database variable; that wasn't included in your post.
Edit: As stated in comments by Riggs, you can use 4 arguments for the connection instead.
I.e.:
$link = mysqli_connect($hostname, $username, $password, $database);
The choice is yours.
Comment:
Much better to put the database as param 4 of the connect. mysqli_select_db() is really only for when you want to switch from one db to another using the same connection – RiggsFolly
...indeed.
In regards to the error:
Fatal error with mysql_select_db()
I hope that you're not mixing this with anything else. Those different MySQL API's do not intermix with each other.
That error alone means that it is "fatal" error as shown and is the result of that API not being supported by your server.
Using PHP's error reporting and set to catch and display, would have (most likely) thrown you an error of deprecation and/or possibly not being supported.
Reference:
http://php.net/manual/en/function.error-reporting.php

changing code to mysqli

I read more than once that is better to use mysqli and than mysql.
I would like to know:
I'm using WAMP for my local server and some share server for my online sites. what do i need to check on php.ini in order to be sure that mysqli will works?
below is my db connection and query code. how would it looks like using mysqli?
$con = #mysql_connect ("localhost", "username", "pass");
if(!$con)
exit("Unable to connect to the Database server");
$db2 = #mysql_select_db("DB_NAME");
if(!$db2)
exit("Unable to connect to the Database");
$query = mysql_query("SELECT somme_filed FROM some_table");
while ($index= mysql_fetch_array($query ))
{
....
}
most of my site was written in mysql. Do I really need to change all the code to mysqli? Is it really so important?
1.As long as you have only one instance of php installed there should not be any problem but if you have more than one instance you may need to point it manually to the version you wish to use. How do I activate mysqli with wampserver?
2.You can use mysqli to connect by doing something like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
3.MYSQL is no longer under development and has been considered deprecated.
Why shouldn't I use MYSQL functions

select database using mysqli in config.php file

I have a nice free for searching a database. It was written with PHP and MySql...however for whatever reason, I occasionally need to add an "i" at the end of MySql occasionally to get things working. I can connect and login, but not select the database, since it passes through until I get the
"request "Unable to select database."
Here's the meat from the config.php file that probably has the issue :
$SETTINGS["hostname"]='localhost';
$SETTINGS["mysql_user"]='root';
$SETTINGS["mysql_pass"]='root';
$SETTINGS["mysql_database"]='myDB';
$SETTINGS["data_table"]='data'; // this is the default database name that we used
/* Connect to MySQL */
if (!isset($install) or $install != '1') {
$connection = mysqli_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('Unable to connect to MySQL server.<br ><br >Please make sure your MySQL login details are correct.');
$db = mysqli_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');
};
?>
The problem you are facing is the line in which you select the database;
$db = mysqli_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');
As defined by the documentation of mysqli_select_db() the connection $connection ($link in the docs) should be the first argument:
$db = mysqli_select_db($connection, $SETTINGS["mysql_database"]);
The reason why you need to occasionally add an i to every mysql_* function is because all mysql_* functions are officially deprecated, no longer maintained and removed in PHP 7.0.0. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.
With mysqli, you can select your database directly using the connection method :
$connection = mysqli_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"], $SETTINGS["mysql_database"]);
If you want to use mysqli_select_db, you need to reverse your arguments. First the connection, then the database :
mysqli_select_db($connection, $SETTINGS["mysql_database"]);

Mysql_error() Not Catching INSERT Error in PHP

new here and really green to programming, so go easy..
I discovered I have an INSERT that is failing because of a duplicate record error. I figured it out by running the query in a MySQL console with literals, where err#1062 popped up.
What I want to understand is why mysql_error() or mysql_errno() didn't catch this error in my PHP script.
Below is a generic setup of what I've done. I have a form that submits to a php file that calls data_insert()
function data_insert($var1, $var2, $var3, $var4){
$db = db_connect();
$query = "INSERT INTO exampletable (id, id_2, id_3, id_4)
VALUES ('$var1', '$var2', '$var3', '$var4')";
$result = $db->query($query);
if (!$result)
{
echo ('Database Error:' . mysql_error());
}
else
{
echo "Data added to db";
}
}
The DB connection:
function db_connect()
{
$result = new MySQLi('localhost', 'root', 'root', 'dbname');
if (!$result)
throw new Exception('Could not connect to database server');
else
return $result;
}
Result I'm getting is:
Database Error:
PHP echos "Database Error:" because the INSERT fails, but no subsequent MySQL error info is echoed. Honestly, I'm not exactly sure what I'm supposed to see, but through reading some other SO questions, I've double-checked my php.ini file for error handling and E_ALL and display_errors is set appropriately (although not sure if it matters in this case).
Is there something in my logic that I'm not understanding, like the scope of the link resource mysql_error() takes?
Thanks for your help, I'm hoping this is something embarrassingly obvious.
I know the above is missing XSS and security precautions and uniform exception handling. Baby steps though. It's simplified here for discussion's sake.
You're using mysqli (note the i) for your DB operations, but are calling mysql_error (no i). They're two completely different interfaces, and do not share internal states at at all. DB handles/results from one are not usable in the other.
Try mysqli_error() instead (note the I).
As far as I can tell, you appear to be using the MySQLi class for connecting and queries, but you're trying to access MySQL error message. MySQLi and MySQL aren't the same, so errors in one will not show in the other. You should look up error handling for MySQLi, not MySQL.
You are confusing two seperate methods for connecting to a mySQL DB.
mysql_error() will only work on queries that are run through mysql_query().
As you are using mysqli, you must use mysqli_error()

Correct Procedure for mysqlConnect

I am new to php syntax and am looking for advice on creating the most acceptable or correct code. I focus on front end design, but I like to make sure my code is proper. I am in a digital media program, my instructor has given us this code for connecting to our MYSQL databases.
<?php
mysql_connect("localhost", "root", "root")or die("Cannot Connect to DB");
mysql_select_db("Example")or die("cannot select the DB Example ");
?>
However when I look at connect scripts online they set the mysql_connect function as a variable lets say $connect and run an if statement stating; if not $connect produce error, and the same for mysql_select_db. They also close the script with mysql_close($connect); like below
<?php
$connect = mysql_connect("localhost", "root", "root");
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("Example", $connect);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
mysql_close($connect);
?>
Is either one better? What problems can I have if I dont close the connect with mysql_close?
Regarding using an if instead of an or, it doesn't matter. The or short-circuits, so if the connection worked, die(...) won't be executed. Using either is a matter of preference. If you want to use the or version while keeping the result of the mysql_connect() call, simply assign the whole expression to a variable:
$connection = mysql_connect(...) or die('Connection failed.');
mysql_close() should be used after you're done with all your database communication.
The other mysql_*() functions will use the connection created by the latest call to mysql_connect() or mysql_pconnect(). If for some reason you want more than one connection, trusting the implicit connection object in this manner will fail. Better is to store the connection object yourself and passing it in wherever you need it.
Also before starting to work with databases, you should be aware that mysql is not secure anymore and is deprecated, you should use mysqli. You can use it also as object oriented language.
more details : http://www.php.net/manual/en/book.mysqli.php
example :
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Categories