Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE
) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}