Save SQL result to variable - mysql

Is it possible to save SQL result in variable and then use that to echo data anywhere on my site.
for example
$result=mysqli_query("SELECT * FROM table");
and then use that variable to show that data anywhere else on site and even repeat it in some loop
$show=mysqli_fetch_assoc($result)
I tried that in for while loop and it echo my result only once.
my full code
$result=mysqli_query("SELECT * FROM table");
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
while( $show=mysqli_fetch_assoc($result))
{echo $show["ID"];}
}

Make a $table1_array and a $table2_array and instead of echo $x use $table1_array[] = $x. Since the table2 - select needs nothing from table1 you should read it only once. Make no inner loop, make two separate loops.
EDIT:
to clarify:
$result=mysqli_query("SELECT * FROM table");
$table_array = array();
while( $show=mysqli_fetch_assoc($result)){
$table_array[] = $show;
}
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
foreach($table_array as $show){
echo $show["ID"];
}
}

Related

How to insert data from a database to array and check it

I need to modify views in an application and I have table user privileges, with a structure like this below
id_staff | feature | capabilities
1 reports view
1 reports create
1 reports edit
2 reports view
2 reports delete
3 reports view
What I need, is where user like id_staff 3 that in reports, feature only have one capabilities, like the example he just can view, can not edit, edit, or create. Then user id 3 only sees hyperlink to view the page, he cannot see hyperlink to create, edit or delete pages.
To do that, I tried to use select query, insert that to array and then compare the array value to getting the condition like above
I have tried to code like this
<?php
$query = $this->db->query('SELECT * FROM tblstaff_permissions WHERE staff_id='.$id.'');
foreach ($query->result() as $row)
{
if($row['feature']=='reports' and $row['capabilities']=='view'){
View
} elseif($row['feature']=='reports' and $row['capabilities']=='delete' ){
Delete
}
}
?>
And then the page is blank
Do you know where's the error ?
Thank you
You could improve it by reducing the repetitive code, like the $row['feature']=='reports' code, like :
$query = $this->db->query('SELECT * FROM tblstaff_permissions WHERE staff_id='.$id.'');
foreach ($query->result_array() as $row)
{
if ($row['feature']=='reports') {
if ($row['capabilities']=='view') {
echo 'View';
} elseif ($row['capabilities']=='delete') {
echo 'Delete';
}
}
}
To get an array result, use the $query->result_array() instead of $query->result(), and also you misses the echo statement.
You are using $query->result() it will give you an array of objects, not an array of array. Also, you are not echoing your links on the view. One more thing you should not use the same condition repeatedly.
In this case, your code should be -
<?php
$query = $this->db->query('SELECT * FROM tblstaff_permissions WHERE staff_id='.$id.'');
foreach ($query->result() as $row) {
if($row->feature =='reports'){
if($row->capabilities=='view'){
echo 'View';
} elseif($row->capabilities == 'delete' ){
echo 'Delete';
}
}
}
?>

How to echo specific mysql data in specific places using php?

If the 'SELECT' statement is used to select data from a database then how do we echo specific rows to specific places on a page using php?
To explain this better - I am trying to SELECT * ALL FROM a table but to echo multiple rows to particular places on the html page using php.
So, imagine that my entire mark up and css has 20 thumbnails on a page and each thumbnail has data and an image that is unique to each thumbnail....do I have to replicate the below 20 times?
I am thinking that the best way to do this (which is probably completely wrong) is to use this statement
SELECT * FROM name_of_table WHERE ID = 4 >>> i.e. where I'd like that specific data echoed....
So, if I have 20 thumbnails do I do this 20 times?
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID = 4;")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'] . "</td> ";
Print "<th>Product:</th> <td>".$info['product_name'] . " </td></tr>";
}
Print "</table>";
?>
And, rinse and repeat but I change the below statement each time for each thumbnail (each thumbnail has unique data that comes from each row on the MySQL)
SELECT * FROM name_of_table WHERE ID = 4;
What is the best way of doing this?
Thanks!
Simple example.. First get the data with wanted ID:s. Create function for data request.
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID IN (2,3,4,5,6);")
or die(mysql_error());
// This holds all data rows
$data_array = array();
while($info = mysql_fetch_array( $data ))
$data_array[] = $data;
// Function for rendering data to html
function getItemHtml($id) {
$html = "";
foreach($data_array as $row) {
if ($row['ID'] == $id) {
$html = "<td>" . $row['title'] . "</td>";
// etc.. create item html here
break;
}
}
return $html;
}
// To create one item just call this with item id.
echo getItemHtml(4);
?>

how use mysql_data_seek with PDO?

I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.

mysql_fetch_array fails sometimes

I'm trying to implement the connection to a online payment framework.
One of the files is giving me some trouble, because sometimes the code works, sometimes it doesn't... And I can't understand why...
Here's where the code is failing...
$sql = "select transidmerchant,totalamount from nsiapay where transidmerchant='".$order_number."'and trxstatus='Verified'";
$result = mysql_query($sql);
**$checkout = mysql_fetch_array($result);**
echo "sql : ".$sql;
$hasil=$checkout['transidmerchant'];
echo "hasil: ".$hasil;
$amount=$checkout['totalamount'];
echo "amount: ".$amount;
// Custom Field
if (!$hasil) {
echo 'Stop1';
} else {
if ($status=="Success") {}
}
It's just part of the code but I think it's enough for you to try to see the problem... It fails on the bold line, $checkout = mysql_fetch_array($result);
The weird thing is that the "echo sql" works, and it shows the right values, but then when I put them on the array, sometimes the variables are passed, sometimes they're not... And so, when getting to if (!$hasil) it fails because the value is empty... but sometimes it works...
Any ideas on what might be happen?
Thans
Luis
The only way this fail is when query doesn't return anything.
The correct way would be to check if there is something returned:
$sql = "select transidmerchant,totalamount from nsiapay where transidmerchant='".$order_number."'and trxstatus='Verified'";
$result = mysql_query($sql);
if($checkout = mysql_fetch_array($result)){
$hasil = $checkout['transidmerchant'];
echo "hasil: ".$hasil;
$amount=$checkout['totalamount'];
echo "amount: ".$amount;
// Custom Field
if (!$hasil) {
echo 'Stop1';
} else {
if ($status=="Success") {}
}
}else{
echo "Empty query result";
}

Help with PHPExcel Library and mySQL data from a table

I have this script
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But in the .xls file it prints only one user. Why id doesnt print all of the users ? W
Thanks in advance.
I make the change you said with $sheet
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$sheet->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But it still prints out only one record. And yes when i run the query in phpmyadmin it returns more than one record.
How can i print out data from mySql table.. What is going wrong ?
I am pretty sure it is because you are using a unique identifier (WHERE tmima_id='6'). It is only finding the results for that one unique identifier and displaying that. Hope this helps.
$i is being reset to row 3 every loop. Set $i=3; before the while loop, not inside it.