bind parameter to pdo function - php

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

Related

Call to a member function fetch() on integer in

I have a problem with a simple pdo query here the query:
$NU=$connection->exec("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";
Since I have no params to bind in the query is correct to use exec without prepare, and how can I fix this problem? (Call to a member function fetch() on integer in )
The exec() method only returns the number of rows effected. You probably want to use query() instead.
$NU=$connection->query("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";
The query() statement will execute a single query and return a PDOStatement object you can fetch from or false on failure.
You need to use query http://php.net/manual/en/pdo.query.php , then you'll have a object with results you can work with.
Try this.
$NU = $connection->query("SELECT COUNT(ID) AS Total FROM USERS");
$result = $NU->fetch();
echo $result['Total'];
What you are looking for is not exec but prepare. From the PHP doc: http://php.net/manual/en/pdostatement.fetch.php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);

Why am I getting this error? Fatal error: Uncaught Error: Call to a member function execute() on boolean in [duplicate]

This question already has answers here:
Fatal error: Call to a member function execute() on boolean
(2 answers)
Closed 5 years ago.
This is my php code:
<?php
$group = filter_input(INPUT_POST, 'groupchooser', FILTER_UNSAFE_RAW,
FILTER_FLAG_STRIP_LOW);
$db = mysqli_connect("localhost", "test", "password", "id3234074_posts");
$stmt = $db->prepare('SELECT TOP 10 titles, comments * FROM $group ');
$stmt->execute(array(':id' => $_GET['id']));
$row = $stmt->fetch();
if($row['id'] == ''){
header('Location: ./');
exit;
}
?>
I have have tried without using prepare and it still gets me a similar error about the boolean.
You have three mistakes in your code:
SELECT TOP X is SQL Server syntax, but judging by the API in your code, you're using MySQL, so you need to use LIMIT X.
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10');
Further, you're biding parameters to the query via execute(), but have no placeholders in it. So, you need to either add them with bind_param() (for example, a WHERE clause), or remove the parameters from execute():
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10 WHERE id = ?');
$stmt->bind_param("i", $_GET["id"]);
$stmt->execute();
Or
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10');
$stmt->execute();
Lastly, you have a couple of fields you're selecting and the wildcard *. You can have this:
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10');
to select titles and comments, or this
$stmt = $db->prepare('SELECT * FROM $group LIMIT 10');
to select all the fields in the $group table.
Sidenote: you're directly embedding client data into your query, and filter_input() isn't helping. You need to be absolutely, positively, 100% sure of what you're inputting into you're query. A safer option could be to have a list of possible groups, and only allow the user to pick one of them:
$group = filter_input(INPUT_POST, 'groupchooser', FILTER_UNSAFE_RAW,
FILTER_FLAG_STRIP_LOW);
$groups = ["group1", "group2"];
if (!in_array($group, $groups)) {
throw new Exception("Invalid group");
}

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.

Fetch_array alternative for PHP prepared statements

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))
{

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