简体   繁体   中英

I am getting errors and warnings in mysqli

UPDATE:

I have a couple of errors and warnings I need help with in mysqli:

Fatal error: Call to undefined method mysqli_stmt::get_result() in ... on line 63

In my code below does anyone know how these warnings and errors can be dealt with?

$query = "SELECT * FROM Teacher WHERE TeacherAlias = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$getid);
// execute query
$stmt->execute();  
//get results
$result = $stmt->get_result(); 

$numrows = mysqli_num_rows($result);
if ($numrows == 0){   

       // don't use $mysqli->prepare here
$query = "SELECT * FROM Teacher WHERE TeacherUsername = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$getuser);
// execute query
$stmt->execute(); 

}

You need to retrieve a mysqli_result object first, with something like...

$res = $stmt->get_result();

... then fetch the number of rows from this object (not $stmt ):

$numrows = mysqli_num_rows($res);

UPDATE: get_result method is available in PHP 5.3+ only, for the older versions one should use the following approach:

// $stmt preparing code goes here...

$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
doSomethingWith($num_rows);

// processing cycle:
$stmt->bind_result($some_param, $another_param);
while ($stmt->fetch()) {
   doSomethingElseWith($some_param, $another_param);
}
$stmt->free_result();
$stmt->close();

As a sidenote, two recommendations: 1) it'd be probably faster to use a single query here and look for value both in TeacherAlias and TeacherUsername fields simultaneously (with OR operator, like TeacherAlias = ? OR TeacherUsername = ? ); 2) it'd be easier to work with explicitly stated columns ( SELECT id, TeacherAlias AS alias, TeacherUsername AS username... ) instead of just ( SELECT * ) in your query.

I'm not used to work with msqli but I will try to answer you, So first of all, yo say the program, "if the result of the request is equal to 0 then restart all again. This is not very good, you're using resources for nothing. Like raina77ow said, you want to use

$res = $stmt->get_result();

and this:

$numrows = mysqli_num_rows($res);

then you don't need anymore your condition if...

You need to fetch your data first, or free_result() .

$stmt->fetch();

Then pass this to mysqli_num_rows()

What i would suggest is, skipping the fetch, if you don't need it and doing:

$stmt->num_rows;

This will count the number of rows in your result without needing to fetch it, and clears the cursor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM