Problem with error "Trying to get property of non-object"

2

I get an error when I'm going to execute my code, it's the following:

Notice: Trying to get property of non-object in C:\xampp\htdocs\results.php on line 61

Number of books found : 

This is the HTML form:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Book-O-Rama</title>
</head>

<body>
	<blockquote>
	  <blockquote>
	    <blockquote>
	      <h1>Book-O-Rama Catalog Search</h1>
        </blockquote>
      </blockquote>
</blockquote>

<form action="results.php" method="post">

<p>Chosse search Type :</p>
<p><select name="searchtype">
	<option value="author">Author</option>
	<option value="title">Title</option>
	<option value="isnb">ISNB</option>
</select></p>

<p>Enter search term :</p>

<input name="searchterm" type="text">

<p><input type="submit" value="Search"></p>

	</form>
</body>
</html>

This is the code in PHP:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Results</title>
</head>

<body>

<?php
	
	// Defino nombre de las variables
	// searchtype : Tipo de busqueda
	// searchterm : Termino de busqueda
	$searchtype=$_POST['searchtype'];		// Recibo los nombres de las variables de los formularios
	$searchterm=$_POST['searchterm'];
	$searchterm=trim($searchterm);		// funcion trim() : Elimina espacios en blanco introducidos involuntariamente con el usuario
	
	if(!$searchtype || !$searchterm){		// Comprobacion de datos que tienen que introducirse , por temas de seguridad
		echo 'You have not entered search details. Please go to back and try again.'; /* No ha ingresado los detalles de búsqueda. Por favor, ve hacia atrás y vuelve a intentarlo */
		exit;
	}
	
	if(!get_magic_quotes_gpc()){		// Funcion vieja , desabilitada en el nuevo PHP 6 , nos indica si las comillas se añaden automaticamente o no , si no se añaden , utilizamos addslashes para escapar
		$searchtype=addslashes($searchtype);		// Se deben filtrar los datos para enviar a una BD
		$searchterm=addslashes($searchterm);
	}
	
	$servername = "localhost";
	$username = "root";
	$password = "";
	$dbname = "books";

	
@ $db= new MySQLi($servername, $username, $password, $dbname); /* HOST,NOMBRE DE USUARIO,CONTRA,NOMBRE DE LA BD */
	// Esta funcion crea una instancia de la clase mysqli
	
	//$db = mysql_connect('localhost','root','');
	
	if ($db->connect_error) {		// Compruebo el intento de conexion
    die("Connection failed: " . $db->connect_error);	// Devuelve el numero de error ( en caso que lo hubiera )
} 

	
	$sql="select * from books where ".$searchtype."like'%".$searchterm."%'";	// Buscamos el valor 
	$result=$db->query($sql); 		// Ejecuto la consulta , devuelve un objeto de resultados

	
	$num_results = $result->num_rows;		// Devuelve el numero de filas , de la forma orientada a 
	
	echo '<p> Number of books found : ' . $num_results.'</p>';
	
	for($i=0; $i<$num_results;$i++)
	{
		$row = $result->fetch_assoc();		//   Obtiene una fila de resultado como un array asociativo
		echo '<p><strong>'.($i+1).'.Title : ';
		echo htmlspecialchars(stripslashes($row['title']));	
		echo '<strong><br />Author: ';
		echo stripslashes($row['author']);
		echo '<br /> ISNB: ';
		echo stripslashes($row['isbn']);
		echo '<br />Price: ';
		echo stripslashes($row['price']);
		echo '</p>';
	}
	
	//$result->free();	// Libera la memoria asociada a un resultado
	$db->close();		// Cierra la conexion previamente abierta en la BD
	
?>
</body>
</html>

This is the original code taken from the book:

Thanks in advance, I'm new to stackoverflow

Greetings!

    
asked by Chehin 27.11.2017 в 02:35
source

2 answers

2

I propose this code, applying some of the concepts indicated in comments. I have not documented it as I would have liked due to lack of time ...

If there is something you do not understand about the code, you can ask it in comments.

Basically:

  • I collect in a variable all the possible errors of the code.
  • I remove the use of @ for being a bad practice. It makes debugging very difficult.
  • I apply prepared queries (security in the code and in the system). SQL injection is a high risk not only at the database level. When you have time documéntate on the subject, right here there is very good information on the subject.
  • I establish a strict control of the code, so that it is not mute in case of possible failures.

Here I leave it, I believe I have not made any mistakes. I hope it serves you.

$db= new MySQLi($servername, $username, $password, $dbname); /* HOST,NOMBRE DE USUARIO,CONTRA,NOMBRE DE LA BD */
// Esta funcion crea una instancia de la clase mysqli

$arrResultado=array();

if ($db->connect_error) {
    $arrResultado["mensaje"]="Connection failed: " . $db->connect_error; // Devuelve el numero de error ( en caso que lo hubiera )
}else{

    $sql="select title, author, isbn, price from books where ".$searchtype." like ?"; // Buscamos el valor

    $stmt=$db->prepare($sql);

    if ($stmt){
        $strLIKE="%".$searchterm."%";
        $stmt->bind_param("s", $strLIKE);
        $stmt->execute();

        $num_results = $stmt->num_rows;  // Devuelve el numero de filas , de la forma orientada a

        if ($num_results){
            echo '<p> Number of books found : ' . $num_results.'</p>';
            $stmt->store_result();
            $stmt->bind_result($titulo, $autor, $isbn, $precio);
            $i=1;
            while ($stmt->fetch())
            {

                echo '<p><strong>'.($i).'.Title : ';
                echo htmlspecialchars(stripslashes($titulo);
                echo '<strong><br />Author: ';
                echo stripslashes($autor);
                echo '<br /> ISNB: ';
                echo stripslashes($isbn);
                echo '<br />Price: ';
                echo stripslashes($precio);
                echo '</p>';
                $i++;

            }

        }else{
            $arrResultado['mensaje']='No se encontraron filas en los resultados';
        }

        $stmt->close(); // Libera la memoria asociada a un resultado

    }else{

        $arrResultado['mensaje']='Error :'.$stmt->error;

    }

    $db->close();  // Cierra la conexion previamente abierta en la BD

}

if ($arrResultado){

    echo $arrResultado["mensaje"];
}
    
answered by 27.11.2017 в 13:31
1

The result variable is not an object since the SQL query is incorrect. since when doing the concatenation $ searchtype the query is wrong why there is no space before the like.

You must correct the SQL query and validate that $ result is different from false before making use of the variable.

If the query does not bring results, you would not have that kind of error. The rpblema is SQL syntax.

    
answered by 27.11.2017 в 05:04