Php MySql While loop if result? - php

Is there a way to tell if there is results before the while loop using this style?
$stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three);
while ($stmt->fetch()) {
}
I would like to do something before and after the while loop but I do not want to query twice.

To check the number of rows selected: $stmt->num_rows
So you might do:
if($stmt->num_rows > 0){
...
}
http://www.php.net/manual/en/mysqli-stmt.num-rows.php

Try
stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three);
$rows = $stmt->num_rows;
if ($rows) {
// your code
}
while ($stmt->fetch()) {
}

you can check with mysqli -> num_rows before while loop
$stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three);
$numrows = $stmt->num_rows;
if ($numrows > 0) {
while ($stmt->fetch()) {
}
} else {
echo "No rows found";
}

Related

Retrieving data from database using prepared statement

I'm having problem retrieving my data from my database. Here's my code:
function login($email, $password) {
$stmt = $this->conn->prepare("SELECT id FROM lms_admin_users WHERE email=?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 1) {
while ($stmt->fetch()) {
// echo data from table like $data["name"]; <----
}
}
else {
echo "Failed";
}
}
What I want to know is the equivalent of while($data=mysqli_fetch_assoc($result)) to replace my existing code (in OOP way) while ($stmt->fetch()) and make it fetch the datas using $data["name"]
You need to tell PHP in which variable(s) to store the result. There are two ways to do this:
with bind_result, and then fetch on the statement object, or
with get_result, and then fetch_assoc (or other fetch_* variant) on the result object
1. bind_result
With this solution you bind variable(s) to the SELECT list, and while looping with fetch PHP will put the new data in those variable(s):
$stmt = $this->conn->prepare("SELECT id FROM lms_admin_users WHERE email=?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $name); // <- Add; #args = #cols in SELECT
if($stmt->num_rows == 1) {
while ($stmt->fetch()) {
echo $id, $name; // <-- then you can do this.
}
}
2. get_result
Instead of bind_result you can use get_result, which will give a result object which you can fetch each row from as an associative array:
//...
// $stmt->store_result(); // <- Remove: does not work together with next statement
$result = $stmt->get_result(); // <--- add this instead
if($result->num_rows == 1) { // <--- change to $result->...!
while ($data = $result->fetch_assoc()) {
echo $data['id'], $data['name']; // <--- available in $data
}
}

correct way to check if user is found in mysql table

The function should return the id of the found user or return false if not found.
Currently I am using bind result and fetch to check if a user is found in an mysql table:
public function getUserIDByName($UserName) {
$uid = "";
$i=0;
if($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")){
$stmt->bind_param("s", $UserName);
$stmt->execute();
$stmt->bind_result($uid);
while($stmt->fetch()){
$i++;
}
$stmt->close();
}
if($i==0){
return false;
}else{
return $uid;
}
}
This works, but I assume that there is a proper way to do this without a counter in the fetch loop. I can not use get_result as mysqlnd is not available.
Simple use num_rows to check your query return result or not
function getUserIDByName($UserName) {
if ($stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?")) {
$stmt->bind_param("s", $UserName);
$stmt->execute();
$row_cnt = $stmt->num_rows;
if ($row_cnt == 1) {
$stmt->bind_result($uid);
while ($stmt->fetch()) {
return $uid;
}
} else {
return false;
}
}
}
Use this instead
public function getUserIDByName($UserName)
{
$uid = '';
$response = false;
$stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name=?");
$stmt->bind_param("s", $UserName);
$stmt->execute();
$stmt->bind_result($uid);
if ($stmt->fetch()) {
$response = $uid;
}
$stmt->close();
return $response;
}
EDIT: just realized you're using mysqli and not pdo. Ill leave this here if you want to use PDO in the feature I guess.
This is how I would do it. You could change rowcount() > 0 to rowcount() === 1 if you want to guarantee only 1 user is found.
public function getUserIDByName($UserName)
{
$stmt = $this->mysqlserver->prepare("SELECT uid FROM user WHERE name = :name");
// bind :name to the username
$stmt->bindParam(":name", $UserName);
// execute the query
$stmt->execute();
// check the rowcount
if ($stmt->rowcount() > 0) {
// fetch the results as a associative array
return $stmt->fetch(PDO::FETCH_ASSOC);
}
// return false because rowcount wasn't bigger than 0
return false;
}

How to handle unknown multiple/single result with php pdo?

I just thought about this case and how to do it a bit more "professional". Does not seem to as if this the way to go even though I do not know any other. Somebody?!
$query = "SELECT col1 FROM ".PREFIX."table WHERE (col2 = :something)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":something", $something, PDO::PARAM_STR);
$stmt->execute();
$stmt->bindColumn(1, $col1, PDO::PARAM_STR);
/* get number of rows */
$num_rows = $dbh->query("SELECT FOUND_ROWS()")->fetchColumn();
if($num_rows == 1) {
$stmt->fetch();
$result = $col1;
} else {
while($stmt->fetch()) {
$result[] = $col1;
}
}

MySQLI prepared failing return results

I have tried thousand of examples but non working, I try to get results on specific row where id= .
My code :
if ($stmt = $func->mysqli->prepare("SELECT * FROM monthlypaymentsrequestlist WHERE id = ?")) {
$stmt->bind_param('s', $user['userid']);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
while ($rows = $stmt->fetch_assoc()) {
echo $row['id'];
}
}
}
The error i get :
Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in
How i do it properly ?
fetch_assoc() is a function of a mysqli_result, not the $stmt Resource you're trying to use. You need to assign it to the return of execute():
if($stmt = $func->mysqli->prepare("SELECT * FROM monthlypaymentsrequestlist WHERE id = ?"))
{
$stmt->bind_param('s', $user['userid']);
// Execute the prepared query.
$result = $stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0)
{
while($rows = $result->fetch_assoc())
{
echo $row['id'];
}
}
}
fetch_assoc is a method of the mysqli_result class, not the mysqli_stmt class.

PHP / MySQLi - How to get value of one row and store in a variable?

I am going through my code and I am running so many queries it is getting long. If I just want to store a single variable with a value, I have to do this:
switch($type) {
case "next":
if ($stmt = $mysqli->prepare("SELECT sort_order FROM user_slides WHERE user_id = ? AND sort_order > ? ORDER BY sort_order LIMIT 1")) {
$stmt->bind_param('is', $user_id, $sortId);
$stmt->execute();
$stmt->bind_result($next_sort_id);
$stmt->store_result();
$stmt->fetch();
return $next_sort_id;
$stmt->close();
}
break;
case "first":
if ($stmt = $mysqli->prepare("SELECT MIN(sort_order) as max_slides FROM user_slides WHERE user_id = ?")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($first_sort_id);
$stmt->store_result();
$stmt->fetch();
return $first_sort_id;
$stmt->close();
}
break;
case "last":
if ($stmt = $mysqli->prepare("SELECT MAX(sort_order) as max_slides FROM user_slides WHERE user_id = ?")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($last_sort_id);
$stmt->store_result();
$stmt->fetch();
return $last_sort_id;
$stmt->close();
}
break;
}
There has to be an easier way to do this. Where I can just do it like this:
$first_sort_id = QUERY HERE
$last_sort_id = QUERY HERE
So it doesn't have to be so long, it can be nice and short.
Does anyone know what I need to do to accomplish that?
First
If you use return the statement $stmt->close(); will be never executed.
Second
Get rid of two vars, you just need one. Don't get fooled by semantic meanings.
Third
A simple reorganization could be this:
switch($type)
{
case "next":
$Query = "SELECT sort_order";
break;
case "first":
$Query = "SELECT MIN(sort_order)";
break;
case "last":
$Query = "SELECT MAX(sort_order)";
break;
}
if ($stmt = $mysqli->prepare("$Query as max_slides FROM user_slides WHERE user_id = ?"))
{
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($value);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $value;
}
else
return NULL;

Categories