mysqli object-oriented

2

What I'm doing wrong I have this sql statement that should throw me 1 and is throwing me 0 my code with prepared query:

<?php
 session_start();
include"conexion.php";

$me=$_SESSION["id"];
$id= $_GET["id"];


$sql=$conexion->prepare("SELECT de,para FROM amigos WHERE de=? AND para=?");

$sql->bind_param('ii', $me, $para);
$sql->execute();

$rows=$sql->num_rows;
  echo $rows;//esto deberia arrojarme 1 pero me arroja 0

$sql->close();


?>

but if the query is not prepared if it gives me the expected result

<?php
 session_start();
include"conexion.php";

$me=$_SESSION["id"];
$id= $_GET["id"];

$sql=$conexion->query("SELECT de,para FROM amigos WHERE de='$me' AND para='$id'");

  echo $sql->num_rows;//resultado esperado 1 

someone can give me a hand I'm just starting to learn the object-oriented form thanks!

    
asked by andy gibbs 25.08.2018 в 05:10
source

1 answer

4

There are two problems in your code:

  • You are capturing the criteria in a variable $id , but in the bind you use a variable $para that does not exist.
  • If you check the num_rows documentation you'll see that this method depends on store_result to work properly:
  

Returns the number of rows in a result set. The use of    mysqli_stmt_num_rows() depends on whether it is used    mysqli_stmt_store_result() to buffer the set of   complete results in the statement manager.

     

If mysqli_stmt_store_result() is used, mysqli_stmt_num_rows() can   call immediately.

That is, if you do not invoke store_result before num_rows , it will be impossible to know the number of rows that the query brought and you will always get 0 for this reason.

The code should work then if we correct those two failures:

<?php
 session_start();
include"conexion.php";

$me=$_SESSION["id"];
$id= $_GET["id"];


$sql=$conexion->prepare("SELECT de,para FROM amigos WHERE de=? AND para=?");

$sql->bind_param('ii', $me, $id);
$sql->execute();

$sql->store_result();    
$rows=$sql->num_rows;
echo $rows;//esto deberia arrojarme 1 pero me arroja 0

$sql->close();


?>
    
answered by 25.08.2018 / 06:41
source