fetch() not returning first row - php

I am trying to update code that has been written using prepared statements. This is my first time using them and I am having difficulty retrieving all the results. When I use a direct SQL statement, it works so I don't think that's the problem.
The code will not return any results until there are at least two that match the query, then it will return all but the first row. I tried using fetchAll, but that gives different error about a call to an undefined method.
Thanks in advance for any help that you can provide. If it's not to much to ask, please provide example or reference I can refer to and complete my understanding.
function html_competitive_make_gallery ($init) {
global $USER;
$user_id = $USER->id;
$page_name = 'competitive';
$base_name = $init['base_name'];
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->bind_param('is', $user_id, $page_name);
$stmt->execute();
$stmt->bind_result($form_id,$community_id);
$stmt->fetch();
$stmt->close();
$sql = "SELECT data FROM tester WHERE type= '".$base_name."'
AND form_id= '".$form_id ."' AND community_id= '". $community_id ."' LIMIT 5";
$stmt = $link->prepare($sql);
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch();
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();
$html[]='</div>';
return implode ( $html);
}

You're running fetch() before entering your loop, hence dropping the first row of your results:
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch(); // <<< THIS LINE SHOULD NOT BE HERE
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();

Try this:
while ($data = $stmt->fetch()){
echo $data;
}
$stmt->close();

Your main problem is called "mysqli".
You will face such problems as long as you're using mysqli with prepared statements.
Just quit it and use PDO:
function html_competitive_make_gallery ($init) {
global $USER;
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->execute(array($USER->id, 'competitive'));
return $stmt->fetch();
}

Related

SQL statement inside while loop PHP

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

Not sure how to echo out the Selected data from mysql

$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if ($stmt->affected_rows > 0) {
echo "Exists";
}
Instead of echoing out Exists, I want it to echo out nameData. How can I go about doing that?
First of all, if you want only one row then append LIMIT 1 to your SELECT query, like this:
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
So there are two approaches to display nameData:
Method(1):
First bind the variable $nameData to the prepared statement, and then fetch the result into this bound variable.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
}else{
echo "No result found";
}
Method(2):
First use get_result() method to get the result set from the prepared statement, and then use fetch_array to fetch the result row from the result set.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
$row = $result->fetch_array()
echo $row['nameData'];
}else{
echo "No result found";
}
I think you can below code i hope your query is working fine it returns result properly then you can use below code.
$stmt->bind_result($nameData);
if ($stmt->fetch()) {
printf ("%s\n", $nameData);
}
Note that affected_rows won't do anything useful here.
However, nor you don't need num_rows as well (and therefore store_result too)
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
Considering all that hassle, even without useless functions, you may find PDO a way better approach:
$stmt = $pdo->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->execute($query);
echo->$stmt->fetchColumn();

Converting mysql functions to mysqli prepared statment keeping the same output

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

How to fetch data from database using prepare statement in php?

I have a database in which I have user_id & associated_id.There can be multiple associated_id for a single user_id. Now I want to fetch all the associated_ids into a single array. I have tried this method but don't know how to get them in array.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
$stmt->bind_param("s", $user_id);
if ($stmt->execute())
{
while ($stmt->fetch())
{
//what to write here
}
//echo var_dump($user);
$stmt->close();
}
Try this:
$stmt = $mysqli->prepare("SELECT associated_id FROM my_contacts WHERE user_id = ?")) {
$stmt->bind_param('s', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($associated_id);
$stmt->fetch();
The results will be stored in the $associated_id array.
You can bind parameters like this and use fetchall method to get all the results in a array
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = :user_id");
$stmt->bind_param(":user_id", $user_id, PDO::PARAM_INT);
if ($stmt->execute())
{
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
//echo var_dump($user);
$stmt->close();
}
According to your code you used mysqli.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
if($stmt->execute()){
$result = $stmt->get_result();
if($result->nom_rows > 0){
while($row = $result->fetch_assoc()){
var_dump($row)
}
}else{
echo "Sorry NO data found";
}
}else{
echo "Some thing is wrong";
}
here you can't used $stmt->bind_result(); instead of use $stmt->get_result()
$stmt->bind_result(); is only used when you define field in select query
with * you need to used $stmt->get_result()
refer this link for more information
Example of how to use bind_result vs get_result

PHP / MySQL Need a Database Class

I need some help. I am working on a project and I found myself writing a bunch of functions for grabbing information from the database:
For Example:
function getSlideByUserAndSortId($sort_order) {
global $mysqli;
global $user_id;
if ($stmt = $mysqli->prepare("SELECT slide_id FROM user_slides WHERE user_id = ? AND sort_order = ?")) {
$stmt->bind_param('ii', $user_id, $sort_order);
$stmt->execute();
$stmt->bind_result($returnSlideId);
$stmt->store_result();
$stmt->fetch();
return $returnSlideId;
$stmt->close();
}
}
function getSlideText($var) {
global $mysqli;
global $user_id;
global $current_slide;
if ($stmt = $mysqli->prepare("SELECT text FROM slide_data WHERE slide_id = ? AND user_id = ? LIMIT 1")) {
$stmt->bind_param('ii', $current_slide, $user_id);
$stmt->execute();
$stmt->bind_result($text);
$stmt->store_result();
$stmt->fetch();
$text = ($stmt->num_rows < 1 ? $var : $text);
return $text;
$stmt->close();
}
}
Which is so messy.. What I need is a class like Codeigniter where I can just do:
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
How does everyone else do it? If you have a lot of information you need to grab and a lot of queries, what is the best way to display the data?
What you're looking for is an Object Relational Mapper and there have been many created for use with PHP and MySql. Some of the best and most widely used are Propel and Doctrine
However you cand find many other suggestions on this stackoverflow question

Categories