Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql php error - quote system

Tags:

php

mysql

I can't get my authors from my php quotes

i have a quotes table: id, quote, aid

i have a author table: id, name, etc...

<?php

$DB_SERVER = "localhost";
$DB_USER = "root";
$DB_PASS = "";
$DB_NAME = "test";
$con = mysql_connect($DB_SERVER, $DB_USER, $DB_PASS);
mysql_select_db($DB_NAME);

$sql = mysql_query("SELECT * FROM quotes WHERE id = ".$_GET['id'], $con);
$row = mysql_fetch_row($sql);

$sql = mysql_query("SELECT * FROM author where aid = " . $row[1], $con);
$row = mysql_fetch_row($sql); 


var_dump($row);

now i get this error Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in /var/www/domain.com/php.php on line 14 NULL

like image 825
Adam Avatar asked Dec 10 '11 20:12

Adam


2 Answers

if you print_r($row); after the first query you will see something like:

Array
(
    [0] => id
    [1] => quote 
    [2] => aid
)

then on your second query you use $row[1] which is the quote (string) and not the number.

$sql = mysql_query("SELECT * FROM author where aid = " . $row[1], $con);

if you echo the error (using mysql_error($con)) you will see something:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'a quote

instead of using mysql_fetch_row use mysql_fetch_assoc and the key of the array will be the name of the column. This way, it's very easy to retrieve data. And don't forget to close your connection.

<?php
$_GET['id'] = 1;
$DB_SERVER = "localhost";
$DB_USER = "root";
$DB_PASS = "";
$DB_NAME = "test";
$con = mysql_connect($DB_SERVER, $DB_USER, $DB_PASS);
mysql_select_db($DB_NAME);
$sql = mysql_query("SELECT * FROM quotes WHERE id = " . (int)$_GET['id'], $con); // or you can use the mysql_real_escape_string
if(!$sql) {
  echo mysql_error($con);
}
$row = mysql_fetch_assoc($sql);
mysql_free_result($sql);

$sql = mysql_query("SELECT * FROM author where id = " . (int)$row['aid'], $con);
if(!$sql) {
  echo mysql_error($con);
}
$row = mysql_fetch_assoc($sql); 
mysql_free_result($sql);

print_r($row);
mysql_close($con);
like image 156
Book Of Zeus Avatar answered Oct 16 '22 05:10

Book Of Zeus


From the manual:

mysql_query() returns a resource on success, or FALSE on error.

mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

So just do some quick error checking

$sql = mysql_query("SELECT * FROM author where aid = " . $row[1], $con);
if ( $sql ) {
    $row = mysql_fetch_row($sql); 
}
else {
    //error
}
like image 20
Galen Avatar answered Oct 16 '22 07:10

Galen