Fetch_array alternative for PHP prepared statements - php

UPDATE
$stmt = $this->db->prepare("
SELECT u.id, u.fname, u.lname, u.mname, u.type, u.email, u.salt,
u.pass, u.salt, u.approved, u.ban, u2.status
FROM `users` AS u
LEFT OUTER JOIN `log` AS u2
ON u2.user_id = u.id
WHERE u.email = ? LIMIT 1") or die($this->db->error);
$stmt->bind_param("s", $_POST['email']) or die($stmt->error);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
die($this->ajax->respond(7));
}
$result = $stmt->get_result();
$data = $result->fetch_array(MYSQLI_BOTH);
Trying to fetch array but getting following error for last line
Fatal error: Call to a member function fetch_array() on a non-object
Can't get it work. Please help

$data = $stmt->fetchAll();
PDO gives this beautiful function for that purpose.
Edit: i thought it was PDO interface. Why you aren't using pdo? I find it way comfortable than mysqli.

mysqli_stmt::execute does not return the result, only true or false. You fetch the result from the mysqli_stmt object itself. Please carefully read the examples at http://php.net/manual/en/mysqli-stmt.execute.php and http://php.net/manual/en/mysqli-stmt.fetch.php.

With get_result() you can get a resultset from the executed statement:
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_BOTH))
{

Related

mysqli prepared statement bind param array of ids

I have simple prepared statement, and i can't find solution to bind list of id's, so as you can see in first statement i get all ids that i need, and in next statement i need to put all those ids into IN clause, but i'm not able to do it, any suggestions how and what is best way to do it ?
$stmt = $mysqli->prepare("SELECT id FROM user WHERE groupId = ? ORDER BY id LIMIT ? OFFSET ?");
$stmt->bind_param("iii", $args['groupId'], $pageSize, $offset);
$stmt->execute();
$stmt->bind_result($id);
$userIds= array();
while ($stmt->fetch()) {
$userIds[] = $id;
}
$stmt= $mysqli->prepare("SELECT a.id as attendantId, a.firstName, a.lastName, c.id as caringId, c.startDate, c.endDate FROM attendant a LEFT JOIN caring c ON c.attendantId = a.id WHERE a.id IN (?)");
$stmt->bind_param('i', $userIds);
$stmt->bind_param('i', implode(',', $userIds));

PHP Mysqli. Need to fetch data from table

This is my code. I execute then nothing happen. Pls check my code
$id = trim(htmlentities($_REQUEST['id'],ENT_QUOTES)); //call the action from previous page
//fetch data
$stmt = $dbi->prepare("SELECT a.telco, a.no_siri, a.no_topup, a.amount, a.requestingAgentID, a.requestDateTime, a.isUsed, b.name FROM card_telco a LEFT JOIN agents b ON a.requestingAgentID = b.id WHERE id = ?"); //query
$stmt->bind_param('s', $id); //binding
mysqli_stmt_execute($stmt); //execute
mysqli_stmt_store_result($stmt); //store the result
$count = mysqli_stmt_num_rows($stmt); //execute rows
$stmt->bind_result($newTelco, $noSiri, $noTopup, $newAmount, $newRequestAgentID, $newRequestDateTime, $isUsing, $newName, $agendId); //binding new result
$stmt->execute() or die(mysqli_error()); //execute the statement
$stmt->store_result() //store new result
$stmt->fetch(); //fetch the data
$stmt->close(); //close the statement
ChromePhp::log('here'); //console
ChromePhp::log($newTelco, $noSiri); //console
Okay i got it!! My query is wrong.
SELECT a.id, a.telco, a.no_siri, a.no_topup, a.amount, a.requestingAgentID, a.requestDateTime, a.isUsed, b.name FROM card_telco a LEFT JOIN agents b ON a.requestingAgentID = b.id WHERE a.id = ?
This is my new query. Thanks for helping me

Left join using PDO

I am using the following PDO query:
<?php
$cadena = $_SESSION[Region];
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT `id_mesero`, `nombre_mesero`,`alias_mesero`, `rest_mesero` FROM tbmeseros WHERE cadena_mesero='$cadena'");
// For Executing prepared statement we will use below function
$STM->execute();
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
foreach($STMrecords as $row)
{
The value from the 'rest_mesero' field is the index from the table 'tbrestaurantes'.
I would need to join some fields values from 'tbrestaurantes' to the PDO query, but I don't know how to do it using PDO.
Any help is welcome.
UPDATED QUESTION TEXT
This is my proposal for the query :
$dbh->prepare("SELECT * FROM tbmeseros LEFT JOIN tbrestaurantes ON tbmeseros.rest_mesero = tbrestaurantes.id_restaurante WHERE tbmeseros.cad_mesero = ?");
But is show an error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound in /.../AdminMeseros.php on line 80
Line 80 is
$STM->execute();
This is my updated query:
<?php
$cadena = $_SESSION[Region];
$STM =$dbh->prepare("SELECT * FROM tbmeseros LEFT JOIN tbrestaurantes ON tbmeseros.rest_mesero = tbrestaurantes.id_restaurante WHERE tbmeseros.cad_mesero = ?");
$STM->bindParam(1, $cadena);
// For Executing prepared statement we will use below function
$STM->execute(array($cadena));
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
foreach($STMrecords as $row)
{
And here table's screenshots:
For tbmeseros:
For tbrestaurantes:
The value of $cadena is 'HQ3'.
When you put a parameter in the SQL, you need to supply the value for the parameter. There are two ways to do that:
1) Call bindParam():
$STM->bindParam(1, $cadana);
2) Provide the values when calling execute():
$STM->execute(array($cadana));
You need to fill the ? in the query:
$q = $dbh->prepare("SELECT * FROM tbmeseros LEFT JOIN tbrestaurantes ON tbmeseros.rest_mesero = tbrestaurantes.id_restaurante WHERE tbmeseros.cad_mesero = ?");
$q->bindValue( 1, 'x' );
$q->execute();
print_r( $q->fetchAll( PDO::FETCH_ASSOC );
In prepare you can use '?' and then bindValue to attach an escaped value to the query. Your query doesn't appear to have this and that is the cause of the error.

bind parameter to pdo function

I am trying to write the below function to display the contents of a MySQL table.
$q=$_GET["q"];
function risk_allocation($db)
{
$result = $db->query("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q");
$result ->bindParam(':q', $q, PDO::PARAM_INT);
return $result;
}
$allocationlist = risk_allocation($db);
I am then calling the finction with:
while($row = $allocationlist->fetch(PDO::FETCH_ASSOC))
{
echo $line['risks'];
echo $line['risktype'];
}
I am receiving error message:
Fatal error: Call to a member function bindParam() on a non-object in /home/she/public_html/versionfour/getrisksperjob.php on line 11
where line 11 is
$result ->bindParam(':q', $q, PDO::PARAM_INT);
I have the feeling this is a simple question resulting from me just being introduced to pdo, but any help appreciated as always.
UPDATE
as per proposed answers, my code is now as below to execute query and to include the variabe q. same error still occurs though. Thanks for help thus far, any ideas?
Fatal error: Call to a member function bindParam() on a non-object in /home/she/public_html/versionfour/getrisksperjob.php on line 11
function risk_allocation($db,$q)
{
$result = $db->query("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q");
$result ->bindParam(':q', $q, PDO::PARAM_INT);
$result->execute();
return $result;
}
$allocationlist = risk_allocation($db,$q);
You have forgotten to execute the query, futhermore you need to prepare instead of calling query:
$result = $db->prepare("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q");
$result->bindParam(':q', $q, PDO::PARAM_INT);
$result->execute();
1.You forgot to execute query
$result->execute();
2.$q is outside function so you will never get value of that inside function. pass $q as second parameter of function
$q=$_GET["q"];
function risk_allocation($db,$q)
{
$result = $db->prepare("select r.risks as risks,r.risktype as risktype,j.job as job from risks r LEFT OUTER JOIN `jobsrisks` j on r.risks = j.risk and j.job=:q");
$result ->bindParam(':q', $q, PDO::PARAM_INT);
$result->execute();
return $result;
}
$allocationlist = risk_allocation($db,$q);

Why do I get this function call error on an non-object when I am calling a function on an object? [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 1 year ago.
Error:
Fatal error: Call to a member function
bind_param() on a non-object in
/var/www/web55/web/pdftest/events.php
on line 76
Code:
public function countDaysWithoutEvents(){
$sql = "SELECT 7 - COUNT(*) AS NumDaysWithoutEvents
FROM
(SELECT d.date
FROM cali_events e
LEFT JOIN cali_dates d
ON e.event_id = d.event_id
WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())
AND c.category_id = ?
GROUP BY DAY(d.date)
) AS UniqueDates";
$stmt = $this->link->prepare($sql);
$stmt->bind_param('i', $this->locationID);
$stmt->execute();
$stmt->bind_result($count);
$stmt->close();
return $count;
}
$this->link->prepare($sql) creates a prepared statement for MySQLi.
Why am I getting this error?
AND c.category_id = ? - there is no table alias c in your query.
Besides that try
$stmt = $this->link->prepare($sql);
if (!$stmt) {
throw new ErrorException($this->link->error, $this->link->errno);
}
if (!$stmt->bind_param('i', $this->locationID) || !$stmt->execute()) {
throw new ErrorException($stmt->error, $stmt->errno);
}
I think the problem is obviously with the prepare function..
The function is probably failing, in which case $stmt would be FALSE and hence not have the bind_param method as a member.
From the php mysqli manual:
mysqli_prepare() returns a statement object or FALSE if an error occurred.
Check your query! Maybe there is a problem with your SELECT statement. And also check for FALSE before trying to execute any member function on what you think is an object returned by the prepare function.
if($stmt === FALSE)
die("Prepare failed... ");// Handle Error Here
// Normal flow resumes here
$stmt->bind_param("i","");
EDIT
I would suspect that the statement may be erroring out because of the sub-query:
SELECT d.date
FROM cali_events e
LEFT JOIN cali_dates d
ON e.event_id = d.event_id
WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())
AND c.category_id = ?
GROUP BY DAY(d.date)
Instead, why don't you write your query like this:
public function countDaysWithoutEvents()
{
$count = FALSE;
$sql = "SELECT COUNT(d.date) ";
$sql .= " FROM cali_events e ";
$sql .= " LEFT JOIN cali_dates d ON e.event_id = d.event_id ";
$sql .= " WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE()) ";
$sql .= " AND c.category_id = ? ";
$sql .= " GROUP BY DAY(d.date) ";
$stmt = $this->link->prepare($sql);
if($stmt !== FALSE)
{
$stmt->bind_param('i', $this->locationID);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch(); // I think you need to do a fetch
// here to get the result data..
$stmt->close();
}else // Or, provide your own error
die("Error preparing Statement"); // handling here
return (7 - $count);
}
P.S. I think you also had a missing a call to fetch as well.. (see example above)
$this->link->prepare this statement is not returning the object
so it is giving you the error

Categories