Started learning PHP and after learning the basic stuff, which was easy because I learn C++ at school and most of the stuff is similar, I started with mysql. Everything works fine, but I can't get to work the connect_errno working.
Copied and pasted this http://php.net/manual/en/mysqli.connect-errno.php into my code with no success.
My few lines of code:
<?php
error_reporting(0);
$db = mysqli_connect('127.0.0.1' , 'root' , '' , 'mydb');
if ($db->connect_errno) {
die('Connect Error: ' . $db->connect_errno);
}
?>
I've also tried an example from a tutorial, no success.
EDIT: ANSWER IS BELOW!
You mixed the Object-oriented approach and the Procedural approach. Below is the example for the OO approach.
$db = new mysqli('127.0.0.1' , 'root' , '' , 'mydb');
if ( $db->connect_errno ) {
die('Connect Error: ' . $db->connect_errno);
}
error_reporting( 0 ); will suppress errors, so if you're in a debugging workflow and need to see those errors, you'll need to update the error reporting directive to error_reporting( E_ALL );.
Also, I updated the db name to mydb as reflected in the code (I switched that out on my local machine to experiment with connections/errors).
You're using a mix of OO and procedural code. mysql_connect does not return an object; it returns a db handle. You can get its error number using the following:
$db = mysqli_connect('127.0.0.1' , 'root' , '' , 'mydb');
$err = mysqli_connect_errno();
Related
I hope this question hasn't been posted/answered elsewhere. Searching didn't yield any satisfactory results so I am posting in the hope that someone will be able to help me out.
I used the code below to display images from mysql database. Used to work perfectly with php 5.6. Today I upgraded to php7 and I simply cannot get it to work.
Displays error message:
Could not get data:.
Here is the code. Please help if you can. Will be highly appreciated.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT * FROM table ORDER BY id DESC LIMIT 5';
mysqli_select_db('my_db');
$retval = mysqli_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_array($retval, mysqli_NUM))
{
echo "{$row[0]}". "<em>" . "({$row[1]})"."</em>"."<br>";
}
mysqli_close($conn);
?>
Thanx for all the helpful comments. I have edited my code. It now displays the path and image filename but not the image. (images/avatars/filename.jpg). Here is the revised code:
mysqli_select_db($conn, 'my_db');
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_NUM))
{
echo "{$row[0]}". "<em>" . "({$row[1]})"."</em>"."<br>";
}
mysqli_close($conn);
?>
Hi guys. I managed to get it working. Thank you all for your assistance and patience. As suggested I changed to echo "<img src='".$row['0']."'/>"."<br>";
echo "{$row[1]}". "<em>" . "({$row[2]})"."</em>";
I think you have the db Link and Query params swapped..
$retval = mysqli_query( $sql, $conn );
Should be
$retval = mysqli_query( $conn, $sql );
There are a few errors in your code.
mysqli_select_db('my_db') requires a db connection as the first parameter.
mysqli_select_db($conn, 'my_db')
However, you could have just as easily used all 4 parameters:
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, 'my_db');
Reference:
http://php.net/manual/en/function.mysqli-connect.php
Then:
mysqli_error() requires a parameter for it.
mysqli_error($conn)
Then:
mysqli_query( $sql, $conn ) You need to inverse those, the connection must be first.
mysqli_query( $conn, $sql )
References:
http://php.net/manual/en/mysqli.select-db.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.query.php
And just to be certain, table if that's your real table name, is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
So wrap it with ticks
$sql = 'SELECT * FROM `table` ORDER BY id DESC LIMIT 5';
Footnotes:
Since MYSQLI_NUM is a constant in PHP, the mysqli_NUM may fail here, so you may need to make it all in uppercase MYSQLI_NUM.
Reference:
http://php.net/manual/en/mysqli.constants.php
Additional notes:
Your question's title holds "Cannot retrieve and display images".
I don't see where you're wanting to display an image here, as there are no <img> tags.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
"Displays error message:
Could not get data:"
This tells me that either your PHP configuration is wrong, or you're accessing it as file:/// rather than http://localhost.
Or, as I already outlined, mysqli_error() requires a db connection parameter where yours does not include it and is erroring out but you're not seeing the message it's throwing.
Use error reporting also and to catch and display:
http://php.net/manual/en/function.error-reporting.php
As Blake outlined in comments:
"Did you update the mysql package, too? PHP7 uses a different package."
So, make sure your installation was successful and that all system files were correctly updated and pointing to the right path/.ini file(s), and that you restarted all services and are running.
Consult Migrating from PHP 5.6.x to PHP 7.0.x:
http://php.net/manual/en/migration70.php
As stated by RiggsFolly in comments:
"You are using mysqli_fetch_array() after doing a SELECT * so we have ZERO idea what columns are returned and what is in any of the columns."
and...
"PS: Using mysqli_fetch_array() with SELECT * is quite dangerous. If someone alters the order of the columns in the database, you are likely to get different columns returned in $row[0] than you where when you tested this code. Use mysqli_fetch_assoc() then you get NAMED columns like $row['id'] and $row['filename']."
I will say this again; you need to use <img src...> in order to show the images. Your code as shown, will not automagically show the images, that's what <img> is for.
I believe that you used to use mysql_*() functions in the previous php version and changed to mysqli when you upgraded to php7.
Although mysqli can be used very similarly to the mysql extension, there are subtle differences.
You can select the default db when you create the connection.
The connection and query parameters are reversed in mysqli_query().
There are other differences as well, so pls read the documentation before adding a letter i to the mysql_*() functions!
I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.
I already know that if you want to connect to a database using MySQL you have to provide the correct URL, username, password that is the normal thing here is my code:
<?php
$mysql_id = mysql_connect('localhost', 'root', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
This code runs well, however if I messed with the username which is root it still connects here is the code:
<?php
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
Can anyone explain to me why is this happening?
As of PHP 5.5.0 mysql_* functions are deprecated and you should not code with thoses. Think of thoses function as a crawling zombie, you don't go and kiss it, do you ?
You should use MySQLi or PDO for doing operations on database. Please don't bother with mysql_* anymore, you dont want that. It's like asking to code on Windows Milenium, hell, even booting this thing is a nightmare.
Anyway, to answer the question you should write :
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
Or better, you should look at the doc of MySqli and be free of thoses shackles. Think about that, please.
You never bothered checking for failure. Your code simply assumes success and blunders onwards.
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
mysql_select_db('Booklet', $mysql_id) or die(mysql_error());
All of the mysql_*() function return boolean false on failure. You need to check for that false. Never ever assume a DB operation succeeded. Always assume failure, check for that failure, and treat success as a pleasant surprise.
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
try to debug your code by adding mysql_error() like this
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
echo " debug return: " . mysql_error();
or simply update your code if you have a newest version of php > 5.5.0
$mysql_id = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
Using the new MySQLi functions, you would get a false back on trying to connect, also you can pass you database as fourth parameter. So your code could look like this:
<?php
if($mysql_id = mysqli_connect('localhost', 'root', '', 'Booklet'))
{
/* do something like mysqli_query($mysql_id, ... */
}
else
{
echo"cannot connect to database ";
}
?>
Environment - PHP5.2.17, MySQL5.0.92
I am implementing an error logging framework in my application and I am trying to log errors and warnings to a database.
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log(mysql_error());
}
...continue code
I wanted to test the logging and passed the wrong host to the mysql_connect function. As expected I got the warning on screen
Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'host' (1) in /path/to/my/php/file.php on line 4
And my log function was called but mysql_error() is null. According to the php manual (http://php.net/manual/en/function.mysql-connect.php), mysql_error() should return the last mysql error. In the manual they even have an example of how to echo the error to the screen using mysql_error().
I tried using mysql_error($db), but it returns an error stating that $db is not defined.
I tried replacing my function with echo mysql_error(); and I doesn't show anything.
I tried using mysql_errno(); and I get null also.
I know the script is catching the warning because it is outputting it to the screen.
One way to resolve my problem is to store the warning in a variable.
I appreciate any help anyone can provide. Thank you.
UPDATE - 2 SOLUTIONS:
SOLUTION 1: (thank you to Mario for suggesting this in one of his comments to this post)
Use PHP function error_get_last() - reference (http://php.net/manual/en/function.error-get-last.php).
New working code with this solution:
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
$error = error_get_last();
log($error['type'] . ": " . $error['message'] . " in file " . $error['file'] . " on line " . $error['line']);
}
...continue code
SOLUTION 2: (thank you to PauPRO for suggesting this in answer 1 below)
Before using $php_errormsg, we need to set track_errors to 1 in the php.ini file. Just include the following line in your php.ini file
track_errors = 1
Alternatively you can set track_errors to 1 inside the script see below the code with this alternative:
ini_set('track_errors', 1);
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log(mysql_error());
}
...continue code
Both solutions work!!!
Make sure you turn on track_errors before using $php_errormsg:
// Preferably do this in your php.ini file, instead of in code.
ini_set('track_errors', 1);
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log($php_errormsg);
}
I have a routine that I call to do a mssql and mysql server connect like so:
$mysql_aoi_conn = DoMySQLConnect( 'AOI' );
$mssql_aoi_conn = DoMsSQLConnect( 'itf' );
the functions are as follows:
function DoMySQLConnect( $pdb_name ){
$mysql_conn = mysql_connect('localhost', '####', '####') or die( 'could not connect to localhost server : ' . mysql_error() );
$mysqldb_conn = mysql_select_db( $pdb_name, $mysql_conn ) or die('could not use database ' . $pdb_name . ' : ' . mysql_error() );
return array("database" => $mysqldb_conn, "connection" => $mysql_conn );
};
function DoMsSQLConnect( $pdb_name ){
$mssql_conn = mssql_connect("128.251.xxx.xxx", '###', '###') or die("failed to connect to server USLONSAPP003");
$mssqldb_conn = mssql_select_db( $pdb_name, $mssql_conn) or die("failed to select database " . $pdb_name);
return array("database" => $mssqldb_conn, "connection" => $mssql_conn );
};
I'm trying to use the connection implementation within the mssql_query and mysql_query to tell my queries which connection to use but I'm getting an error. Here is one of my queries:
$login_res = mssql_query("SELECT *
FROM ITF_USER
WHERE ITF_LOGIN = '" . $lcUserName . "'", $mssql_aoi_conn['connection'] )
or die("failed to query ITF_USER: \n" . mssql_get_last_message() );
This dies with the mssql_get_last_message() of:
Changed database context to 'itf'. which is not really an error. Can someone tell me if I'm utilizing this query option wrong?
After some research it seems that mssql_query() doesn't support the link_identifier option and therefore breaks (albeit without a valid error for debugging). Removing the link identifier for the mssql_query and keeping it throughout my document for any mysql_query() lets me use both mssql_query() and mysql_query() commands throughout my script.
Even though you have solved your problem, I was facing a similar error "changed database context" when using the mssql_exec() function in PHP. It seems to be fixed by setting:
sqlsrv_configure ( "WarningsReturnAsErrors" , 0 ); //OFF
sqlsrv_configure ( "LogSeverity" , 1 ); //SQLSRV_LOG_SEVERITY_ERROR
Before that, I was using [DATABASE].[dbo].[TABLE] to prevent getting lots of reports about such error/warning.