The executing script does mostly nothing but call the following function. This problem doesn’t happen if I am not inserting anything beforehand (and just select the entire table).
function create_author()
{
$config = config();
$database = mysql_connect($config['database']['hostname'], $config['database']['username'], $config['database']['password']);
mysql_select_db($config['database']['database']) || die('Cannot select database');
$table = 'authors';
$values = array();
$values[] = sprintf(
'first_name = "%s"',
mysql_real_escape_string($_POST['first_name'])
);
if (array_key_exists('middle_initial', $_POST) && !empty($_POST['middle_initial'])) {
$values[] = sprintf(
'middle_initial = "%s"',
mysql_real_escape_string($_POST['middle_initial'])
);
}
$values[] = sprintf(
'last_name = "%s"',
mysql_real_escape_string($_POST['last_name'])
);
if (array_key_exists('biography', $_POST) && !empty($_POST['biography'])) {
$values[] = sprintf(
'biography = "%s"',
mysql_real_escape_string($_POST['biography'])
);
}
$query = sprintf(
'INSERT INTO %s SET %s;',
$table,
implode(', ', $values)
);
mysql_query($query, $database) || die(mysql_error());
$genre_id = mysql_insert_id($database);
$query = sprintf(
'SELECT * FROM authors WHERE id = %u LIMIT 1;',
$genre_id
);
echo $query, PHP_EOL, '<br />', PHP_EOL;
$result = mysql_query($query, $database) || die('Failed to read author.');
//header('Content-Type: application/json');
echo '$result: ', is_bool($result) ? ($result ? 'true' : 'false') : strval($result), PHP_EOL, '<br />', PHP_EOL;
echo 'Number of selected rows: ', mysql_affected_rows($database), PHP_EOL, '<br />', PHP_EOL;
echo 'Error: ', mysql_error($database), PHP_EOL, '<br />', PHP_EOL;
mysql_close($database);
echo json_encode(mysql_fetch_assoc($result));
}
This gives the following output:
SELECT * FROM authors WHERE id = 27 LIMIT 1;
$result: true
Number of selected rows: 1
Error:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in file_path.php on line 89 null
Using a different SQL client, the above SELECT
query returns a row. I am using PHP 5.3.3.
The “duplicate” questions don’t seem to answer the question.
Before the anti-mysql_*
bandwagon rolls around the corner, I am using a server in which I have no control over for a school project. The server is controlled by the IT department. The pdo_mysql and mysqli extensions are not installed. Additionally, there are no other SQL extensions enabled except for the sqlite extension (which wouldn’t suffice since I need to use foreign keys). And the system administrator will not make changes. The point is that I have no choice but to use the mysql_*
functions.
Advertisement
Answer
Using the ||
operator converts the result to a boolean value.