PHP Fetch all rows from MySQL - php

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

Related

What is the proper way to bind to different values in PDO equal to mysqli?

I have been converting a small login script i did to PDO trying to give it a try.
Code mysqli
$stmt = $conn->prepare('SELECT id, name FROM users WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $name);
if ($stmt->fetch()) {
$_SESSION['id'] = $id;
$_SESSION['name'] = $name;
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}
I changed to PDO
$sql = "SELECT id, name FROM users WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->execute();
if ($stmt->fetch())
{
$_SESSION['id'] = $id;
$_SESSION['name'] = $name;
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}
in mysqli i was able to bind and store $id and $name but read those were not available in PDO
$stmt->store_result();
$stmt->bind_result($id, $name);
There's no equivalent of bind_result in PDO because you don't really need it. Just read the data from the row:
if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row["id"];
$_SESSION['name'] = $row["name"];
$is_valid = true;
}
You also don't need the $stmt->bindParam(':name', $name); line because there is no :name input parameter in your SQL.
More examples are available in the manual and elsewhere.
See also Is it possible to use store_result() and bind_result() with PHP PDO? for more useful background info.
The equivalent method is called bindColumn(). You can bind a variable to one column in the result set.
/* Bind by column number */
$stmt->bindColumn(1, $id);
$stmt->bindColumn(2, $name);
while ($stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $id. "\n";
}
However, I would recommend writing simpler code. PDO is designed to be easier to use.
If you want to make the code simpler, use arrays. The method fetch() returns an array with the current row. They are better when you need to fetch more than one column from the result. If you only need to fetch one column, use fetchColumn().
$sql = "SELECT id, name FROM users WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute([
'id' => $id,
'name' => $name,
]);
if ($row = $stmt->fetch()) {
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}

mysqli array fetching is not getting data

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

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();

Return the id (auto increment) of an inserted line

I insert data into a table called 'roster'. The first column (id_roster) is an id using mysql auto-increment.
I run a SELECT to find the id_roster
I use this id_roster to insert it into a table 'roster_par_membre' along with other data
if ($insert_stmt = $mysqli->prepare("INSERT INTO `roster`(`nom_roster`, `description_roster`, `id_organisation`, `created_by`, `creation_date`,`modified_by`) VALUES (?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssiisi', $roster_name, $description_roster, $organisation_id, $user_id, $creation_date, $user_id);
if (!$insert_stmt->execute()) {
$reponse = 'Sorry, a database error occurred; please try later';
} else {
// if INSERT OK -> create a new line in roster_membre table
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
$level = 1;
//2. create a line with the roster_id and insert the membre as level 1
$insert_stmt = $mysqli->prepare("INSERT INTO `roster_par_membre`(`id_membre`, `id_roster`, `level`, `modified_by`) VALUES (?,?,?,?)");
$insert_stmt->bind_param('iiii', $user_id, $id_roster, $level, $user_id);
$insert_stmt->execute();
$reponse = 'success';
}
So far the code is working but it is not very nice.
Is there a way when we create a new line in a table to directly return a value (id with auto-increment) to be used in a sql query (to insert data into a second table)? or maybe to merge the two query (the two INSERT) in one statment?
short edit: it is an AJAX $response the return value (JSON)
Ok,solution:
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
Just need to replace all this part by
$id_roster = $mysqli->insert_id;
nice and easy. THANKS to albanx
these are the functions I used for query on projects that I do not want to use any framework (just php):
/**
*
* Executes query methods
* #param string $query the query string
* #param array $vals array of values
* #param bool $show show the query
* #return int/array/false
*/
function q($query, $vals=array(), $show_query=false)
{
$conn = new mysqli(...)
$offset = 0;
foreach ($vals as $v)
{
$cv = $conn->real_escape_string($v);//escape the value for avoiding sql injection
$fv = ($v===NULL) ? 'NULL':"'".$cv."'"; //if value is null then insert NULL in db
$qpos = strpos($query, '?', $offset);//replace the ? with the valeue
$query = substr($query, 0, $qpos).$fv.substr($query, $qpos+1);
$offset = $qpos+strlen($cv)+1;
}
$result = $conn->query($query);
if($show || $result===false) echo $query."<br>";
$rows = array();
if($result===true)
{
return $conn->affected_rows;
}
else if($result===false)
{
return false;
}
else
{
while ($row = $result->fetch_array(MYSQLI_ASSOC) )
{
$rows[]=$row;
}
}
return $rows;
}
function lastid()
{
return $this->qval("SELECT LAST_INSERT_ID()");
}
Usage example:
q('INSERT INTO USER(name, email) VALUES(?,?)', array('admin','admin#admin.com'));
$id = lastid();

Return mysqli query result as an array in PHP

I've been searching the internet for a while now, but since I'm new to MySQLi, I cannot solve this problem myself. This is my code so far. I want to return the result as an array.
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo)) {
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error.' in query: '.$userinfo;
} else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$var] = &$$var;
}
return $parameters;
}
$stmt->close();
}}
Hopefully someone can help me get this code working, or help me find an alternative.
Have you looked at using fetch_array
http://php.net/manual/en/mysqli-result.fetch-array.php
Working from your code
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo))
{
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute())
{
echo $stmt->error.' in query: '.$userinfo;
}
else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$parameters = array();
while ($row = $stmt->fetch_assoc()) {
$parameters[] = $row;
}
$stmt->close();
return $parameters;
}
$stmt->close();
}
}

Categories