mysqli array fetching is not getting data - php

I have to fetch result in single row but I can't run multiple rows. How can I fix this?
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
$stmt->close();
return $result;
}
I Got Result Like Wise This
{"ID":2,"Name":"Anju"}
But i need to get all user result .my code is here
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = array();
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row;
}
$stmt->close();
return $result;
}
I got the error
Fatal error: Call to a member function fetch_array() on a non-object in line 5
The line is:
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC))
my expecting result is
{"ID":1,"Name":"Obi"}, {"ID":3,"Name":"Oman"}, {"ID":4,"Name":"Anju"}

$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bindValue(1, $id);
Try that way
And try to fetchAll instead of fetch_array

You could make following correction.
Change
$rows->fetch_assoc(MYSQLI_ASSOC)
to
$rows->fetch_assoc()
It should look like
if ($stmt->execute()) {
$rows = $stmt->get_result();
$result = array();
while ($row = $rows->fetch_assoc()){
$result[] = $row;
}
$stmt->close();
return $result;
} else {
return NULL;
}
Suggestion : Always specify the list of columns in your SELECT, which makes query execution faster.
Please read php manual

Related

PHP Fetch all rows from MySQL

I'm trying to fetch all rows for parentId for my form. However my below code isn't able to fetches just 1 record, into my array:
public function getChildByParent($parentId)
{
$stmt = $this->conn->prepare("SELECT childId, nick, relation FROM childId WHERE parentId = ?");
$stmt->bind_param("s", $parentId);
$stmt->execute();
$stmt->bind_result($childId, $nick, $relation);
$stmt->fetch();
$user = array();
$user['childId'] = $childId;
$user['nick'] = $nick;
$user['relation'] = $relation;
return $user;
}
I understand that I need to tweek around $stmt->fetch() and $user = array() to fetch_all. Can you help me work around this code?
Appreciate your efforts.
Using $stmt->get_result() to setup $result->fetch_all() to get all records in one call.
Try:
public function getChildByParent($parentId)
{
$stmt = $this->conn->prepare("SELECT childId, nick, relation FROM childId WHERE parentId = ?");
$stmt->bind_param("i", $parentId);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
return $user;
}

i write DB fetch code in function but it does not work?

I write this below function for Fetch fields from DATABASE but it does not work :
function Refresh_TBL_post() {
global $conn;
#DB Query Comment
$stmt = $conn->prepare("SELECT * FROM post WHERE id=? ");
$stmt->bind_param("s", $_REQUEST['editpostId']);
#Run Query In DB
$stmt->execute();
#Get Count Of Rows
#Refrsh $stmt
$stmt->get_result();
$row = $stmt->fetch_assoc();
return $row;
}
And i call this function like this Refresh_TBL_post();
but it does not works . How can i fix it ?
#Refrsh $stmt
$stmt->get_result();
$row = $stmt->fetch_assoc();
return $row;
is not the same as what you did last.
You should do this:
function Refresh_TBL_post() {
global $conn;
#DB Query Comment
$stmt = $conn->prepare("SELECT * FROM post WHERE id=? ");
$stmt->bind_param("s", $_REQUEST['editpostId']);
#Run Query In DB
$stmt->execute();
#Get Count Of Rows
#Refrsh $stmt
$res = $stmt->get_result();
return $res->fetch_assoc();
}
Calling with:
$row = Refresh_TBL_post();
Which should work. You fetch from get_result and not from stmt in your last post.
I changed function to below :
function Refresh_TBL_post()
{
global $conn;
#DB Query Comment
$stmt = $conn->prepare("SELECT * FROM post WHERE id=? ");
$stmt->bind_param("s",$_REQUEST['editpostId']);
#Run Query In DB
$stmt->execute();
#Get Count Of Rows
#Refrsh $stmt
$stmt = $stmt->get_result();
return $stmt;
}
and use like this
#Refresh
$stmt_Refresh_Tbl_post=Refresh_TBL_post();
$row=$stmt_Refresh_Tbl_post->fetch_assoc();
or like this
#Refresh
$row=Refresh_TBL_post()->fetch_assoc();

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;
}

fetchAll(PDO::FETCH_ASSOC) not returning a single value

When I use the code below I get Undefined Index: email on $row['email']. If I grab the whole array with $row and print_r, it displays like it should.
Where am i going wrong ?
$stmt = $db->dbh->prepare("SELECT email FROM $this->table WHERE `email`= :email");
$stmt -> bindValue(':email', $email);
$stmt->execute();
while ($row = $stmt->fetchAll()){
return $row['email'];
}
$new = new Users;
echo $new->reset_password($email);
}
fetchAll returns a 2-dimensional array of all the results. To get just one row at a time, you should call $stmt->fetch(), not $stmt->fetchAll().
while ($row = $stmt->fetch()) {
...
}
But since you're returning, you shouldn't use a loop at all. The return statement will terminate the loop after the first iteration. Just use an if statement.
if ($row = $stmt->fetch()) {
return $row['email'];
}
This whole code doesn't make much sense -- $newemail is guaranteed to be the same as $email, why are you returning it? It probably should be:
if ($stmt->fetch()) { // Email was found
return true;
} else {
return false;
}
to check if the email entered in the db,
$stmt = $db->dbh->prepare("SELECT 1 FROM $this->table WHERE email= ?");
$stmt->execute([$email]);
return $stmt->fetchColumn();
You should use this code:
while ($row = $stmt->fetch()){
$newemail = $row['email'];
}
Instead of this code:
while ($row = $stmt->fetchAll()){
$newemail = $row['email'];
}
Method fetchAll() fetches all rows in a single call, method fetch() fetches only current row and moves pointer to the next row.
Documentation to method fetch() can be found here and documentation to method fetchAll can be found here.

Can't get array from PDO query

i'm trying to get an array from a SQL query using pdo, what i send to the method it's for example $connection->selectFrom('Person',array(1,2));
when i try to get the results it returns an empty array, here is my code:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
// HERE I GET ALL THE COLUMN NAMES FROM THE TABLE I RECEIVE
$columns = $this->getColumnNames($table);
$finals = array();
// IN THIS CICLE I GET THE COLUMNS THAT MATCH THE INDEXES I RECEIVE
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
// FROM HERE I GET THE QUERY STATEMENT WICH IS SELECT column1,column2 from $table
$query = $this->getSelectSQL($table, $finals);
// ALL OF THE ABOVE WORKS BUT HERE IT STOPS WORKING
$results = $pdo->query($query);
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Thanks to #Cymbals for your answer, the final code ended up like this:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
$columns = $this->getColumnNames($table);
$finals = array();
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
$query = $this->getSelectSQL($table, $finals);
$query.= " WHERE Available = 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt ->fetchAll();
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Try this after getting the query, prepare and execute it
$stmt = $pdo->prepare($query);
var_dump($stmt);// if the prepare fails or sql query is messed up it will give false
$results = $stmt->execute();
return $results;

Categories