try to read data from a MySql database obtaining a "Try to get non-object property" [duplicate]

Advertisement

This question already has an answer here:

Reference - What does this error in PHP mean?

9 replies

I wrote a program that
Creates a database
Create a table
Insert data into it
Read the data

After executing the sql statement to read the data, I get a
"Trying to get non-objection property"
When I try to see if the query contains ant data
$ sql = "SELECT time FROM data";
$ result = mysql_query ($ sql, $ link);

if ($ result-> num_rows> 0) Crashes here

Complete program

// connect to databases
$ link = mysql_connect ('localhost', 'root', 'xxxxxxx');
if (! $ link) {
echo 'Connection error:'. mysql_error (). "\ not";
die ('Could not connect:'. mysql_error ());
}

// create a database
$ sql = 'CREATE DATABASE bitcoin';
if (mysql_query ($ sql, $ link)) {
echo "Database my_db created successfully \ n";
} other {
echo 'Error creating the database:'. mysql_error (). "\ not";
}

// table creat
mysql_select_db ('bitcoin');
$ sql = "CREATE TABLE bitcoin data id INT NOT NULL AUTO_INCREMENT, time BIGINT NOT NULL, price DOUBLE NOT NULL, tradeid INT NOT NULL, side INT NOT NULL, PRIMARY KEY ( id ) ENGINE = InnoDB;

  $retval = mysql_query( $sql, $link ); if(! $retval ) { echo('Could not create table: ' . mysql_error()); } echo"table created"; 

// insert data
$ sql = "INSERT INTO data ( id , time , price , tradeid , side ) VALUES (NULL, '999999999999', '1', '2', '3');
mysql_select_db ('bitcoin');
$ retval = mysql_query ($ sql, $ link);

  if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n"; 

// get data
$ sql = "SELECT time FROM data";
$ result = mysql_query ($ sql, $ link);

if ($ result-> num_rows> 0) {
// output data of each line
while ($ row = $ result-> fetch_assoc ()) {
echo $ row ["time"] ;;
}
} other {
echo "0 results";
}

The answer

You mix database interfaces. If you use the mysql_ functions (which you should not), you have to stick to it. So this line:

 if ($result->num_rows > 0) 

It should:

 if (mysql_num_rows($result) > 0) 

However, mysql_ functions have been deprecated from PHP 5.5 and removed from PHP 7, so they should not be used for all modern applications. Apart from this, they are prone to SQL injection and, in general, should not be used if they can be avoided.