I am trying to gather some variables from my query then output them using $stmt->bind_result() however I am not getting any rows returned in my search.
I am not sure what is going wrong here?
$tag = trim($_GET['tag']);
$stmt = $mysqli->prepare('SELECT trips.trip_id FROM trips JOIN tags ON trips.post_id = tags.post_id WHERE tag = ?');
$stmt->bind_param('s', $tag);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
echo $id;
}
Related
I am trying to run a SQL statement within a while loop, using the variable $id set in the previous statement but am struggling to get it working. If I remove the statement in the while loop I can see the while loop is functioning as it displays the $id variable multiple times:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
echo "ID: " . $id . "<br>";
}
However when I add the SQL statement back in, I am presented with only the first $id result. If I add in $stmt->close(); at the start of the while loop I do get the first company name, but then the while loops ends. Here is the code:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
Any ideas please?
Update: If I add in a store result before the loop and free result inside the loop I get the first company name and also get the "finished loop" echo:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
while ($stmt->fetch()) {
$stmt->free_result();
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
echo "finished the loop";
}
Thanks.
Cant comment so answering here.
I think you need to use $stmt->bind_param("s", $businessPark); instead of $stmt->bind_param("s", $num);
I had it working (albeit with different queries) on my test server - I'm pretty sure the issue is that you need to pass the resultset through to PHP so that you can prepare the second statement (which must be outside the loop) - otherwise sql = $conn->prepare( ... ); fails and returns false.
This should work:
$businessPark = $_SESSION['businessPark'];
$num = "1";
//first statement
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
//pass the result to PHP so you can prepare a new statement
$stmt->store_result();
//second statement
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
while ($stmt->fetch()) {
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
//clean up
$stmt->free_result();
$stmt->close();
You can accomplish what you want with a join. I know that this does not answer why your code is not working but in my opinion it's a better solution anyway.
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("
SELECT t2.CompanyName
FROM Portal.services t1
INNER JOIN phpipam.ipaddresses t2 ON t1.CompanyId = t2.id
WHERE " . $businessPark . " = ?
");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($companyName);
More information about join syntax
The array showcasef holds 20 items per page. I do 3 different queries within the foreach loop, which is 60 queries (just for the loop, there's additional queries too).
<?php
foreach($showcasef as $itemf){
$sf_id = $itemf['sf_id'];
$sf_url = $itemf['sf_url'];
$sf_title = $itemf['sf_title'];
$sf_urltitle = post_slug($sf_title);
// Fetch number of favs
$stmt = $conn->prepare("SELECT COUNT(f_id) FROM favourites WHERE f_showcaseid=?");
$stmt->bind_param("i", $sf_id);
$stmt->execute();
$stmt->bind_result($numfFavs);
$stmt->fetch();
$stmt->close();
// Fetch class
$stmt = $conn->prepare("SELECT avg(r_class) FROM ranks WHERE r_showcaseid=?");
$stmt->bind_param("i", $sf_id);
$stmt->execute();
$stmt->bind_result($sf_class);
$stmt->fetch();
$stmt->close();
// Fetch number of classes
$stmt = $conn->prepare("SELECT COUNT(r_class) FROM ranks WHERE r_showcaseid=?");
$stmt->bind_param("i", $sf_id);
$stmt->execute();
$stmt->bind_result($numfClasses);
$stmt->fetch();
$stmt->close();
?>
Render HTML here
<?php } ?>
Will this be a severe performance issue, or are these particular queries relatively simple? If I keep the columns indexed, should it perform okay with millions of rows (potentially)? Or can the queries be optimized/simplified?
Here's how I get the showcasef:
$stmt = $conn->prepare("SELECT s_id,s_url,s_title FROM showcase WHERE s_userid=? ORDER BY s_date DESC LIMIT $skippingFactor, 20");
$stmt->bind_param("i", $u_id);
$stmt->execute();
$stmt->bind_result($sf_id,$sf_url,$sf_title);
while($stmt->fetch())
{
$showcasef[] = [
'sf_id' => $sf_id,
'sf_url' => $sf_url,
'sf_title' => $sf_title
];
}
$stmt->close();
A few suggestions here.
Reuse prepared statements
You are creating three prepared statements inside the loop. Why don't you create your statements only once, and then reuse them using multiple binds?
<?php
$stmt1 = $conn->prepare("SELECT COUNT(f_id) FROM favourites WHERE f_showcaseid=?");
$stmt1->bind_param("i", $sf_id);
$stmt1->bind_result($numfFavs);
$stmt2 = $conn->prepare("SELECT avg(r_class) FROM ranks WHERE r_showcaseid=?");
$stmt2->bind_param("i", $sf_id);
$stmt2->bind_result($sf_class);
$stmt3 = $conn->prepare("SELECT COUNT(r_class) FROM ranks WHERE r_showcaseid=?");
$stmt3->bind_param("i", $sf_id);
$stmt3->bind_result($numfClasses);
foreach($showcasef as $itemf) {
$sf_id = ...
$stmt1->execute();
$stmt1->fetch();
/* if the fetch succeedes then $numfFavs will contain the count */
$stmt2->execute();
...
$stmt3->execute();
..
}
$stmt1->close();
$stmt2->close();
$stmt3->close();
Use a single query to Count the rows and calculate the average
You can combine the second and third statement a single SQL query:
SELECT COUNT(r_class) AS cnt, AVG(r_class) AS average
FROM ranks
WHERE r_showcaseid=?
Use a single query instead a foreach loop
With the previous suggestions you can get better performances. But are you really sure you need a foreach loop?
If your IDs are returned by another query, instead of a foreach loop is better to use a subquery:
SELECT f_showcaseid, COUNT(f_id)
FROM favourites
WHERE f_showcaseid IN (SELECT id FROM ... WHERE ...)
GROUP BY f_showcaseid
or you can provide a list of IDs to the query:
SELECT f_showcaseid, COUNT(f_id)
FROM favourites
WHERE f_showcaseid IN (?,?,?,?,?)
GROUP BY f_showcaseid
(you can dynamically create the list of ? if the number of IDs is not fixed)
You could do this in a single query I think.
Something like the following:-
SELECT f_showcaseid, COUNT(f_id), avg(r_class), COUNT(r_class)
FROM ranks WHERE r_showcaseid IN (".implode(',', $showcasef).")
GROUP BY f_showcaseid
Of course, to use parameters you would need to do that a bit more elegantly:-
<?php
$stmt = $conn->prepare("SELECT f_showcaseid, COUNT(f_id), avg(r_class), COUNT(r_class)
FROM ranks WHERE r_showcaseid IN (".implode(',', str_split(str_repeat('?', count($showcasef)), 1)).")
GROUP BY f_showcaseid");
foreach($showcasef as $itemf)
{
$stmt->bind_param("i", $itemf['sf_id']);
}
$stmt->execute();
$stmt->bind_result($numfClasses);
$stmt->fetch();
$stmt->close();
?>
I'm currently going thorough a site and replacing all the functions which used to return mysql_fectch_array() results, which are put into while loops elsewhere. I'm trying to make them return the same data in the same format but by using mysqli prepared statements output. I have been successful with the code below in producing the same formatted output for single row results.
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT * FROM email_setting WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $this->user);
$stmt->execute();
$stmt->bind_result(
$row['email_id'],
$row['user_id'],
$row['news'],
$row['new_message'],
$row['new_friend'],
$row['rule_assent'],
$row['agreement_ready'],
$row['agreement_all_assent'],
$row['time_cap'],
$row['donations']
);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $row;
}
But how can I get this code to work when it returns more than one row? I want it to be produce the same result as if I had written:
return mysql_fetch_array($result);
Is it possible?
Consider the following adjustment, passing query results into an associative array:
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT email_id, user_id, news, new_message,
new_friend, rule_assent, agreement_ready,
agreement_all_assent, time_cap, donations
FROM email_setting
WHERE user_id = ? ");
$stmt->bind_param("i", $this->user);
$stmt->execute();
// CREATE RETURN ARRAY
$row = [];
// OBTAIN QUERY RESULTS
$result = $stmt->get_result();
// ITERATE THROUGH RESULT ROWS INTO RETURN ARRAY
while ($data = $stmt->fetch_assoc()) {
$row[] = $data;
}
$stmt->close();
return $row;
}
You will notice I explicitly select the query's fields to avoid an indeterminate loop through query results.
Ok I have managed to get it to work without using get_result()
This is how I did it with alot of help from Parfait and Example of how to use bind_result vs get_result
function saved_rules($user){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT R.rule_id, R.rule_title
FROM Savedrules S
LEFT JOIN Rule R
ON S.saved_rule_id = R.rule_id
WHERE S.saved_user_id = ?");
$stmt->bind_param("i", $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $rule_title);
while ($stmt->fetch()) {
$result[] = Array("rule_id"=>$id,"rule_title"=>$rule_title);
}
$stmt->free_result();
$stmt->close();
return $result;
}
Its not exactly the same output as using a mysql_fetch_array() so where it is used I have to change the loop to:
foreach($saved_rules AS $row){}
from
while ($row = mysql_fetch_array($saved_rules){}
I don't know why this query won't return a value because when I copy the "echoed" portion into phpmyadmin I do get a record returning:
echo $_GET["cname"];
// Query template
$sql = 'SELECT C.cid FROM `Contact` C WHERE C.email="'.$_GET["cname"].'"';
echo $sql;
// Prepare statement
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result( $res_cid);
echo $res_cid;
$res_cid is apparently 0, but I don't know why because when I paste that query manually into phpmyadmin I do get a value... So why doesn't it return anything?
As already mentioned in the comments - you should make sure your code is secured. You better use the bindparam for that.
As for your question - after you execute your query and bind_result you should also fetch to get the actual value from the database, based on your query:
// Prepare statement
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result( $res_cid);
// Fetch to get the actual result
$stmt->fetch();
echo $res_cid;
hope someone can help me.
i have a very simple prepared SELECT statment in PHP:
$query_select = ("SELECT * FROM companies where user_name = ? ");
$stmt = $mysqli->prepare($query_select);
$stmt->bind_param("s", $user_name);
$stmt->execute();
$count = $stmt->num_rows;
in companies table I have several rows with the $user_name i`m trying to query. But i still get 0 rows as a result.
The strange thing is that the non PREPARED version works:
$query = 'SELECT * FROM companies WHERE user_name="'.$user_name.'"';
$result = $mysqli->query($query);
$count= $result->num_rows;
echo "Aantal: ".$count;
So my question is, does anyone know why the prepared version returns ZERO and the non prepared version returns the correct number of rows?
Add this line to your code between execute and num_rows statement.
$stmt->store_result();
You have to store it before counting it.
For mysqli prepared statements, you must take an additional step: storing the result.
Try this:
$query_select = ("SELECT * FROM companies where user_name = ? ");
$stmt = $mysqli->prepare($query_select);
$stmt->bind_param("s", $user_name);
$stmt->execute();
$stmt->store_result(); // <-- new line
$count = $stmt->num_rows;
May be you need to bind the result:
/* bind result variables */
$stmt->bind_result($district);
Full example here