this is my code
global $wpdb;
foreach( $wpdb->get_results("SELECT * FROM detail_buyer ORDER BY id DESC LIMIT 1") as $key => $row)
{
$barang=$row->nama_barang;
//in this table field 'nama_barang' have values more than one
}
echo $barang;
but output result look like this
tempe
any idea how I could do this?
Remove the LIMIT in your query,
SELECT * FROM detail_buyer ORDER BY id DESC
For keep your results of values, you need to create an array variable and store into them.
like this
$barang[] =$row->nama_barang;
Try this,
global $wpdb;
foreach( $wpdb->get_results("SELECT * FROM detail_buyer ORDER BY id DESC LIMIT 1")
as $key => $row)
{
$barang[] =$row->nama_barang; // changes made here
//in this table field 'nama_barang' have values more than one
}
print_r($barang);
Change your code to this :
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM detail_buyer ORDER BY id DESC");
$barang = array();
foreach( $results as $key => $row)
{
$barang[] = $row->nama_barang;
//in this table field 'nama_barang' have values more than one
}
echo implode(', ', $barang);
I've deleted the LIMIT 1 witch was limiting your request to 1 result.
PS : Never put your query directly in your loop instruction.
Edit : For more explanation, I replace your variable by an array, I keep each value in it, and at the end I show our array as a string (using ', ' as separator).
Related
From mysqli request I receive a result that contains a table with 5 columns and a number of rows. I would like to perform a calculation with my data that I just received and add the result of my calc in a NEW COLUMN in my array.
So in different words, I would like to add one column to the array and fill this column with results for each row.
My code so far looks as follows and of course only prints the array that I receive from my SQL query:
<?php
error_reporting(0);
require 'init1.php';
if($result = $db->query("Select * from (select * from(SELECT * FROM `scores`
ORDER BY `battle_id` ASC,user_id asc,score desc) as t1 GROUP BY
t1.battle_id, t1.user_id) as t2 order by `battle_id` ASC,score desc")){
if($count = $result->num_rows){
echo '<p>' , $count, '<p>';
while ($row = $result->fetch_object()){
echo $row->battle_id, ' ' , $row->user_id, ' ' , $row->score, '<br>';
}
//instead of just printing the existing array, I would like to perform a
//calculation and add a result in a new column at the end of every single
//row
}
}
If you use an Array you can simply 'define' a new item in your array to store the calculation result.
while ($row = $result->fetch_row()) {
// Calculation and other stuff here
$row['calc_result'] = $calculation_result;
}
Then in order to access it outside the while scope, you would need to store each row in another array, for example:
$stored_data = array();
while ($row = $result->fetch_row()) {
// Calculation and other stuff here
$row['calc_result'] = $calculation_result;
array_push( $stored_data, $row );
}
I'm trying to fetch the last 100 row but only one row is being displayed as a result
here is my php code:
<?php
require_once("variables.php");
$db = new ezSQL_mysql($GLOBALS['database_username'],$GLOBALS['database_password'],$GLOBALS['database_database'],$GLOBALS['database_server']);
header('Content-Type: application/json');
echo "{\"office\":\"0\",\"dept\":{\"desk\":[";
$symbols = addslashes($_GET['symbols']);
$symbolsArr = explode(",", $symbols);
foreach($symbolsArr as $s) {
$last = $db->get_row("select * from data where name='$s' order by id desc limit 0,100");
$jsonArray = array('name' => $s,
'phone' => $last->phone,
'active' => $last->active);
echo json_encode($jsonArray);}
echo "]}}";
?>
UPDATE> based on recommendations below I have changed get_row to get_results but the code broken now and it's not displaying any error.
Read the documentation on the database class you are using (ezSQL):
----------------------------------------------------
Example 2
----------------------------------------------------
// Get one row from the database..
$user = $db->get_row("SELECT name,email FROM users WHERE id = 2");
echo $user->name;
echo $user->email;
You are issuing a statement that is specifically to fetch one single row.
What you want to use is get_results() method instead of get_row() method.
I re-read your question and see that you were doing limit 0,100 which returns 100 rows starting with 0 (first). i thought you were trying to cycle those rows but I can see you are actually trying to only get the last row... my bad, derp.. well here - you are reversed somewhat in your query - should be 100,1 as you want the 100th row and only 1 row.
$last = $db->get_row("select * from data where name='{$s}' order by id desc limit 100,1");
$jsonArray = array('name' => $s,
'phone' => $last->phone,
'active' => $last->active);
Since you are trying to get last 100 rows use following statement:
$last = $db->get_results("select * from data where name='$s' order by id desc limit 100");
instead of
$last = $db->get_row("select * from data where name='$s' order by id desc limit 0,100");
ezSql get_results is the method which you need to use for retrieving multiple results from database.
I am running a sql query, that pulls the id, catid, name, subof from two tables using inner join.
select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name
Now this results everything i need but I need to loop through the result and do another sql query for the subof value (which is a value, the value being a ID number of the shop_cat). I need to pull the catname of the subof value #, then update the result/array field subof to the name of the cat.
So if the original query gave me a value of 15 for subof, it would do a select catname from shop.cat where id='15' i would take the catname from that query and then update subof = catname for every value in the original result that has a subof value.
EDIT 3/23/13 12:30pm MST: Using more of the code that Opeyemi wrote, to explain more of what I need. I am not sure how else to explain it...
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
$getname = mysql_query("select catname from shop_cat where id='$subof'");
$rowname = mysql_fetch_assoc($getname);
//code to update array to change value of $subof to new $rowname['catname']
}
The DB query runs, gets me my values.
I then need to run a loop of some kind, which will loop through every result PHP aquired from the query. This loop will take the subof value (which is a integer ID number) then run a query to get the value catname of that integer value. Then the loop will update the current result and change the subof value from the integer to the catname pulled from the DB in the loop.
I do not need to update the database at anytime, I need to update the result/array from the first query.
What you need to do is to store the resultset in an array and replace within the array.
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
$dataset = array();
// Store result in an array
while($assoc = mysql_fetch_assoc($r)) {
$dataset[] = $assoc;
}
// Update array
foreach($dataset as $data) {
$getname = mysql_query("select catname from shop_cat where id='{$data['subof']}'");
$rowname = mysql_fetch_assoc($getname);
// replace data
replace_dataset($data['subof'], $rowname);
}
function replace_dataset($key, $newname) {
global $dataset;
foreach($dataset as $k => $data) {
if ($data['id'] == $key)
$dataset[$k]['subof'] = $newname;
}
}
Are you asking how to do this in PHP or what? If you are looking for how to loop results in PHP it is as simple as this
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
// the values from the query are assigned to the variables
// $shopid, $catid, $name, $catname, $subof in that order already
mysql_query("update shop_cat set subof=catname where id='$subof'");
// My interpretation of your query can be wrong though
// But you should get the idea
}
You can use mysql_fetch_assoc() or mysql_fetch_array() or mysql_fetch_row() functions to fetch the row and can put your looping concept on it.
After that you can use mysql_fetch_field() to fetch field subof and id from it.
and update the database after that
You can check the following links
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
http://www.php.net/manual/en/function.mysql-fetch-field.php
I hope you get some idea.
The code below only outputs single line(there are 2 in database that should be outputed).
I think that problem is in id=$data[id] since data1 is array instead of single value.I hoped that while will fix that but it doesnt look too good...
$results1 = mysql_query("SELECT * FROM keywords WHERE keyword='$search' ORDER BY (relevant-irrelevant) DESC");
$data1=mysql_fetch_array($results1);
$results2=mysql_query("SELECT * FROM searchengine WHERE id='$data1[id]'");
while($data2=mysql_fetch_array($results2))
First, isolate your ids, looping to get all of the results:
$ids = array();
while ( $data1 = mysql_fetch_array($results1) ) {
$ids[] = $data1['id'];
}
Then, convert your $ids array into a string. An easy way to do this is via implode():
$results2=mysql_query(
"SELECT * FROM searchengine WHERE id IN (" . implode(',', $ids) . ")"
);
Maybe I´m missing something, but how can $data1['id'] be an array? it´s probably an integer and perhaps a string, but it's not an array. $data1['id'] is a single value; the value of field id in the keywords table
I think you just need to put curly quotes around the variable:
$results2=mysql_query("SELECT * FROM searchengine WHERE id='{$data1[id]}'");
or even better:
$results2=mysql_query("SELECT * FROM searchengine WHERE id=" . (int) $data1['id']);
If id is an integer that is.
And of course if the first query returns more than 1 result, you will have to loop through them as well.
Couldn't you just select the entire thing in one query?
SELECT *
FROM keywords k
searchengine s
WHERE k.keyword='$search'
AND k.id = s.id
$results1 = mysql_query("SELECT * FROM keywords WHERE keyword='$search' ORDER BY (relevant-irrelevant) DESC");
$data1=mysql_fetch_array($results1);
//VERY DANGEROUS TO USE USER INPUT
$in = join(',',$data1['id']);
$results2=mysql_query("SELECT * FROM searchengine WHERE id IN ({$in})");
while($data2=mysql_fetch_array($results2))
You can't pass array as condition. You should:
a. do a for(each) loop in the $data1 array and perform next actions
b. implode the array and search with IN. Example:
$commaSeparated = implode(",", $data1);
$results2=mysql_query('SELECT * FROM searchengine WHERE id IN ('.$commaSeparated.'));
mads.ohm is correct about combining the two queries into a single query.
As for your problem with only getting one return value, your while loop is just overwriting the contents of $data2 each time through.
You could write something like this instead:
$i = 0;
$data2 = array();
while ($row = mysql_fetch_array($results2)) {
$data2[$i] = $row;
$i++;
}
In this case, $data2 is declared as an array, and each iteration of the while loop adds a row from the database to the array.
I'm trying to make a function which will display the top X results of the row Y which I set, for this instance I'm using the row browser and the top 5 results from my table statistics, the where is just to eliminate Search Bot results from showing up. I also want it to return the count of the amount of rows as well. So say there was 10 results for the browser 'Safari', then it would return the count of 10 for that result as well as the result itself.
$display->show_list('statistics', 'browser', '5', 'WHERE browser!=\'Search Bot\'');
Here is my function. I'm cleaned it up a bit to remove certain checks and outputs if the query were to fail, etc.
function show_list($table, $row, $limit = 5, $where = NULL) {
$item = mysql_query("SELECT DISTINCT $row FROM $table $where LIMIT $limit");
$result = array();
while ($fetch = mysql_fetch_array($item)) {
$result[] = $fetch;
}
return $result;
}
Not sure I understand the question, but what about using a group by clause, in your SQL query :
select your_column, count(*)
from your_table
where ...
group by your_column
order by count(*) desc
limit 5
That would get you :
for each value of your_column,
the number of rows with that value
and you'd keep the 5 values of your_column that have the biggest number of rows
Change this line:
$item = mysql_query("SELECT $row, count(*) as rows FROM $table $where GROUP BY count(*) ORDER BY count(*) DESC LIMIT $limit");
After doing that, you may not want to mix this with your generic show_list function.
A random note. DISTINCT tends to be somewhat expensive on the database. I would avoid defaulting to doing it.
Incidentally your indentation is..interesting. No decent programmer will want to work with that code without reformatting to some consistent indentation scheme. There are endless arguments about the best way to format, but the following would be a reasonable indentation of your original code:
function show_list($table, $row, $limit = 5, $where = NULL) {
$item = mysql_query("SELECT DISTINCT $row FROM $table $where LIMIT $limit");
$result = array();
while ($fetch = mysql_fetch_array($item)) {
$result[] = $fetch;
}
return $result;
}
function show_list($table, $column, $limit = 5, $where = '') {
$item = mysql_query("SELECT $column, COUNT(*) AS c FROM $table $where
GROUP BY $column ORDER BY c LIMIT $limit");
$result = array();
while ($fetch = mysql_fetch_array($item)) {
$result[] = $fetch;
}
return $result;
}
Replace row with column - we are actually passing a column name in the variable.
Replace $where = null with $where = '' - it will ensure that the query works correctly even when $where is null.
Modify the query to generate the expected results (to the best of my understanding of your question)
Re-format the code and indent it properly.