The code I have is the following
$sql = <<<SQL
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6
SQL;
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
echo $array;
However I am getting an error, I am just trying to get the results into an array. Does anyone know how I can achieve this?
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /var/sites/c/xxxxxxx/public_html/index.php on line 26
Thanks!
$sql = mysql_query("
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6";
$array = Array();
while ($row = mysql_fetch_array( $sql )) {
$array[] = $row;
}
echo "<pre>";
print_r( $array );
You have the sql statement, byt forgot to send it to mysql.
...
$result = mysql_query($SQL); // you forgot this
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
var_dump($array) ; // not echo $array
Related
UPDATE :
i need get a all values of tags field !
MY Query :
$query = db_select('node', 'node');
$query->fields('tagsdata',array('name'));
$query->fields('node', array('nid'));
$query->leftJoin('field_data_field_tags', 'tags', 'tags.entity_id = node.nid');
$query->leftJoin('taxonomy_index', 'tagsindex', 'tagsindex.nid = tags.entity_id');
$query->leftJoin('taxonomy_term_data','tagsdata','tagsdata.tid = tags.field_tags_tid AND node.nid = tagsindex.nid');
$result = $query->execute();
while( $record = $result->fetchAssoc() ) {
$items[] = $record;
}
AND MY CODE :
//SORT
array_multisort(array_column($items, 'nid'), $items);
foreach ($items as $row) {
$hash[$row[nid]] = $row;
}
$resultfinal = ($hash);
// END SORT
foreach($resultfinal as $finalarrays)
{
$tags=$finalarrays['name'];
print_R ($tags);
}
WITH above code just return one and first value of tags, i need to print all of them !
You can use GROUP_CONCAT mysql function to get all value imploded by comma :
$result = db_query("SELECT tags.entity_id as nid, GROUP_CONCAT(t.name) as tdata FROM field_data_field_tags
INNER JOIN taxonomy_term_data t ON t.tid = tags.field_tags_tid
WHERE tags.entity_type = :type GROUP BY tags.entity_id",
array(':type' => 'node'))->fetchAllKeyed();
NB : sometimes you have too much string to concat so you need to increase limit before by :
db_query('SET SESSION group_concat_max_len=10000');
$result = db_query("SELECT tags.entity_id as nid, GROUP_CONCAT(t.name) as tdata FROM field_data_field_tags
INNER JOIN taxonomy_term_data t ON t.tid = tags.field_tags_tid
WHERE tags.entity_type = :type GROUP BY tags.entity_id",
array(':type' => 'node'))->fetchAllKeyed();
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
foreach($result as $nid => $tags) {
echo $nid . ' : '.$tags;
}
I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}
my database table is named order. it has a row like order. I store values like this 1,2,3,4,5. Now i would like to add to array and from it out info..
I tried to do that but it is not working...
here is my code:
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
if want check print_r($array) Output
Array ( [0] => 1,23,4,5 )
this one is not working.. i think its supposed to be like this: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
FASTEST APPROACH
You need to use explode() function. Here is an example of it :
<?php
$array = array('0' =>'1,2,3,4,5');
$array = explode(',', $array[0]);
var_dump($array);
?>
Here is your updated code, to get array in that format.
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
$array = explode(',', $array[0]);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
Note this is solution which you are looking for. But it isn't recommended due to reason told to you as comment.
PROPER WAY TO HANDLE THIS
You should ideally normalize your Database so this kind of problem don't come even in future to you.
Here is a proposed table structure change, which you can consider, depending on your need & time.
Remove order column from your table. Add a new table named order_suborders as follows:
| COLUMN | TYPE |
|:-----------|------------:|
|parent_order| int |
| order_id | int |
You can change name of columns and table according to your wish.
Move old data accordingly.
Use query SELECT order_suborders.order_id FROM order, order_suborders WHERE order.id = ".$_GET['id']." AND order.id = order_suborders.parent_order
you can use explod to split with ","
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
//$array = array($sql_order);
$array=explod(",",$sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
I have this JSON which has the same ord_name , cust_id , Ord_num
{"orders":[{"id":"1","ord_name":"Nestea Bottle","ord_desc":"Nestea in a bottle","ord_price":"15","ord_qty":"2","customer_id":"54feec24bff73","ord_num":"13211554feec24bff73","price_x_quan":"30.00","image":"http://192.168.43.52/MMOS/uploads/nestea_bottled.jpg","subtotal":"","imgimg":"uploads/nestea_bottled.jpg"},{"id":"2","ord_name":"Nestea Bottle","ord_desc":"Nestea in a bottle","ord_price":"15","ord_qty":"4","customer_id":"54feec24bff73","ord_num":"13211554feec24bff73","price_x_quan":"60.00","image":"http://192.168.43.52/MMOS/uploads/nestea_bottled.jpg","subtotal":"","imgimg":"uploads/nestea_bottled.jpg"},{"id":"3","ord_name":"Nestea Bottle","ord_desc":"Nestea in a bottle","ord_price":"15","ord_qty":"1","customer_id":"54feec24bff73","ord_num":"13211554feec24bff73","price_x_quan":"15.00","image":"http://192.168.43.52/MMOS/uploads/nestea_bottled.jpg","subtotal":"","imgimg":"uploads/nestea_bottled.jpg"}],"o_total":[{"total":"105"}]}
my problem is , how to merge or just Overwrite programmatically the JSON with the 'same' ord_num , customer_id and ord_name
field that will update are qty = 7 , price_x_quan
What i want : Nestea in a bottle will have qty = 7 , price_x_quan = 105
this is my code for ordershow
<?php
mysql_connect('localhost','root','')or die ('No Connection');
mysql_select_db('dbmoms');
//$ord = $arr['ord_num']
$sum=0;
$total = $sum;
$sql1 ="SELECT * FROM orders ORDER BY id desc LIMIT 1";
if($row=mysql_fetch_array(mysql_query($sql1))){
$order_id=$row['ord_num'];
}
$sql ="SELECT * FROM orders WHERE ord_num = '$order_id' ";
$result = mysql_query($sql);
$arr["orders"] = array();
while($row = mysql_fetch_assoc($result)){
$arr['orders'][]= $row ;
$sum = $sum+$row['price_x_quan'];
}
$arr['o_total'][] = array('total' => "$sum" );
$json_encoded_string = json_encode($arr);
$json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
echo $json_encoded_string;
?>
please help !
Above:
$arr['orders'][]= $row ;
Put:
// Specify custom values for Nestea..
if( $row[ 'ord_desc' ] == 'Nestea in a bottle' )
{
$row[ 'ord_qty' ] = '7';
$row[ 'price_x_quan' ] = '105.00';
}
You can do this right in your MySQL query using SUM function with a GROUP BY clause.
As a side note you should consider using mysqli (where the trailing i stands for improved) or PDO for accessing your database, instead of the deprecated mysql interface. Now why on earth should I bother to do that?
$sql1 ="SELECT * FROM orders ORDER BY id desc LIMIT 1";
if($row=mysql_fetch_array(mysql_query($sql1))){
$order_id=$row['ord_num'];
}
// Use SUM and GROUP BY to let the database do the math, introducing
// the calculated 'sum_price_x_quan' and 'sum_ord_qty' columns
$sql = "
SELECT ord_num,
ord_desc,
sum(price_x_quan) as sum_price_x_quan,
sum(ord_qty) as sum_rod_qty
FROM orders
WHERE ord_num = '$order_id'
GROUP BY ord_num
";
$result = mysql_query($sql);
$arr = array();
if ($row = mysql_fetch_assoc($result)) {
$arr['orders'][] = $row ;
$arr['o_total'][] = array('total' => $row["sum_price_x_quan"]);
}
$json_encoded_string = json_encode($arr);
echo $json_encoded_string;
Output:
{
"orders": [
{
"ord_num": "13211554feec24bff73",
"ord_desc": "Nestea in a bottle",
"sum_price_x_quan": "105.00",
"sum_ord_qty": "7"
}
],
"o_total": [
{
"total": "105.00"
}
]
}
I have this function:
function findAllmessageSender(){
$all_from = mysql_query("SELECT DISTINCT `from_id` FROM chat");
$names = array();
while ($row = mysql_fetch_array($all_from)) {
$names[] = $row[0];
}
return($names);
}
that returns all the ID of my users in a private messaging system. Then I want to get the all the messages where the user_id is equal to the user logged in and from_id is equal to all from_id I got from the previous function:
function fetchAllMessages($user_id){
$from_id = array();
$from_id = findAllmessageSender();
$data = '\'' . implode('\', \'', $from_id) . '\'';
//if I echo out $ data I get these numbers '113', '141', '109', '111' and that's what I want
$q=array();
$q = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
$try = mysql_fetch_assoc($q);
print_r($try);
}
print_r return only 1 result:
Array (
[id] => 3505
[from_id] => 111
[to_id] => 109
[message] => how are you?
[sent] => 1343109753
[recd] => 1
[system_message] => no
)
But there should be 4 messages.
You have to call mysql_fetch_assoc() for each row that is returned. If you just call mysql_fetch_assoc() once then its only going to return the first row.
Try something like this:
$result = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
'mysql_fetch_assoc' returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
You need to iterate array like:
while ($row = mysql_fetch_assoc($q)) {
echo $row["message"];
}