I am struggling to append data retreived from an SQL query in PHP. Basically I have this so far -
$sql = "SELECT * FROM product WHERE productId = '1'";
$result = mysql_query($sql);
if(mysql_affected_rows() > 0){
while($row = mysql_fetch_assoc($result)){
extract($row);
$response["Sales"][]["Products"]["SaleProduct"] = array('ProductName'=>$ProductName);
}
}
This will work for the most part. It will append to each array, however where I am stumbling is if the SQL returns more than 1 row...
Baically I am tryign to return an array in a web service, it will return "Sales" made. Each Sale could have many products in it. With the code I have so far it only caters for one product per sale. If 2 products are sold then it will essentially create 2 sales with 1 product each.
Can anyone guide me in the correct way to be able to get what I need?
Thanks
Based on your description, this sounds like what you are after:
$response["Sales"]["Products"][] = array('ProductName'=>$ProductName);
The general problem is that you are not using the [] syntax carefully enough. It's a good idea to only use that at the end of the expression.
Related
I have 2 tables, 1 with companies(Costcenters) and one with clients (employees of those companies)
i need to make a form to edit or delete malformed ( like john smit and j. Smit) from those companies employees grouped by company (Costcenter), when i make a list with all those companies i get a lot of companies that has no clients. So I made a array of the companies (Costcenters) and check first if they have employees, this with the goal to remove the Costcenters without employees from the array ($bedrijven).
The form is no problem, but i cant find a way to get those companies removed from the bedrijven array.
require_once('conn.php');
$query = "SELECT bedrijfID, Houder, Costcenter, Actief FROM bedrijven
WHERE Actief = 'actief' ORDER BY Costcenter";
$results = mysqli_query($conn, $query);
if (!$results) printf("Query failed: %s\n", $conn->error);
$bedrijven = [];
while($row = mysqli_fetch_assoc($results)) {
$bedrijven[] = $row['Costcenter'];
}
foreach ($bedrijven as $key => $item) {
$query1 = "SELECT * from customer where Costcenter = '$item' ORDER by
Client";
$customerresult = mysqli_query($conn, $query1) or
die(mysqli_error($conn));
if (!$customerresult) printf("Query failed: %s\n", $conn->error);
if($customerresult->num_rows === 0) {
unset($bedrijven[$key]);
}
}
I am not familiar with PDO or funtions so tried it this way that does not work as i expected, the unset is not working.
the code is editted as it is working now, i hope it might help others as well. If any has a better solution please post.
If I understand what you are going for, this is better done as a single Query. A JOIN can be used first to bind your tables, and then additional WHERE operators can be used if needed to refine your search. I'm not 100% sure if I'm reading right that this is is exactly how you wanted to join the data, but if you play with different JOIN operators you'll get it.
$query = "SELECT Costcenter.bedrijfID, Costcenter.Houder, Costcenter.Costcenter, Costcenter.Actief, customer.* FROM Costcenter
LEFT JOIN customer ON customer.Costcenter = Costcenter.Costcenter
WHERE Actief = 'Costcenter.actief' AND Costcenter.Costcenter != "" ORDER BY Costcenter.Costcenter";
The biggest reason for doing it this way this that a single SQL call processes WAY faster than trying to parse your data from multiple calls in PHP.
thanks to the requestion of The fouth bird i discovered i have been wasting a lot of time on a simple solution. i should not have done :
unset($bedrijven['Costcenter']);
but
unset($bedrijven[$key]);
you must unset the key in the array not the value....
I want to get how many (possibly 0) times a particular number occurs in a particular column. I set the number in $contact_client_ID then do the SELECT query below.
$sql = "SELECT * FROM t_contacts WHERE contact_client_ID ='$contact_client_ID'";
$result=(mysqli_query($link, $sql));
$count_result= mysqli_num_rows($result);
echo "contact client ID $contact_client_ID xxxxx $count_result";
Instead of $count_result containing the number I want, it contains a result made up of the number I want and the contact_client_ID joined together and the result doesn't seem to be usable as a number in any following code.
So, if $contact_client_ID = 50 and there are 2 occurrences of it in the table, the output I get is:
contact client ID 50 xxxxx 250
I've looked at the manuals and examples all over the place (including here) and I can't see what I'm doing wrong.
There are multiple ways of doing this, more precisely you have the option, to either do the count in PHP, or make your SQL server do the counting and just return the number:
Do it in PHP:
What it requires is: - fetch all data; -make a counter variable; - loop trough the data, for each loop increase counter +1
For small tables you can use PHP, for bigger ones I advice doing it on the SQL, since for PHP to count it it must fetch all the data.
$counter=0;
$query = "SELECT * FROM t_contacts WHERE contact_client_ID ='$contact_client_ID";
$res = $con->query($query);
while ($row = $res->fetch_assoc()) {
$counter++;
}
Do it in SQL
Now the smarter way would be to do it on the SQL server ,as it would handle the load better;
I would say what /u/Adaleni wrote is pretty close to what I would use:
$sql = "SELECT count(contact_client_ID) as total FROM t_contacts WHERE contact_client_ID ='$contact_client_ID'";
$result=mysqli_query($link, $sql);
$count_result= mysqli_fetch_row(result);
echo "contact client ID $contact_client_ID xxxxx $count_result[0]['total']";
Lets just describe what he does:
we use COUNT() function in SQL, this makes the server count the number of occurances of contact_client_ID and then make (in the result) a new variable called "total"
we execute the query and get the result
We use mysqli_fetch_rowm this function gets the result row as an enumerated array
then we access that array (as we know its only 1 item, we accessed index 0) and we print the variable total which we made in step 1 - $count_result[0]['total']
Try this
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM t_contacts WHERE contact_client_ID ='$contact_client_ID")) {
printf("Select returned %d rows.\n", $result->num_rows);
im trying to display a tracking number for a product on opencart.
so once the order has been placed. i then add a tracking number to it. from which i wish the customer to be able to see on the order history.
// get tracking details
$sql = 'SELECT * FROM '.DB_PREFIX.'order_history'.`tracking_number`;
$query = $this->db->query($sql);
$rates = array();
foreach($query->rows as $result){
$rates[] = $result;
}
$this->data['tracking'] = $tracking;
this would also go in order.php
this is what ive written but it dont work, im not expert at php, i dabble in it. hopefully someone can point me in the right direction,
so this code would go into controller/account/order.php
then on the template i assume i can just insert
<?php echo $tracking; ?> to display tracking deteails.
thanks in advance.
Off hand, I can see that this code will result in error, because your quotes/backticks are out of place:
$sql = 'SELECT * FROM '.DB_PREFIX.'order_history'.`tracking_number`;
Should be more along these lines:
$sql = "SELECT `tracking_number` FROM `".DB_PREFIX."order_history`";
And, assuming you're going to want to pull an order-specific tracking #:
$sql = "SELECT `tracking_number`
FROM `".DB_PREFIX."order_history`
WHERE `order_id` = 'MUFFINS'";
Do yourself a favor and use the double quotes when preparing a MySQL query. It's easier to wrap your stuff in single quotes without having to escape.
As for the remainder of the code, these are not rates but tracking numbers. Assumedly, there would be one tracking number to return per order, which you could wrap up into a single line of code like so:
$my_tracking_number = $this->db->query("
SELECT `tracking_number`
FROM `".DB_PREFIX."order_history`
WHERE `order_id` = 'MUFFINS'
")->row['tracking_number'];
if ( !empty($my_tracking_number) {
$this->data['tracking_number'] = $my_tracking_number;
}
However, if you're going to associate more than one tracking number with an order you can either insert a BLOB column in your order_history table and insert/query serialized data, or create a separate table entirely where multiple rows can be associated with a single order ID.
I want to read the last 3 rows of my table seperate and then place them in 3 different div's of a slider. The problem is that i cant use 'where id=xxx' because i insert rows dynamically every time that i make a post item.
if i use query('select * from news order by id desc limit 3') and then a loop while ($result->fetch_assoc()) then i have the last 3 rows.
My problem is that i want to place every row in a different div so that i will have 3 divs.
I suppose i must do 3 different queries for that but i dont know how.
I have this one right now.
$result = $myDb->query('select * from news order by id desc');
while ($nI = $result->fetch_assoc()) {
$title = $nI['title'];
$date = $nI['date'];
$author = $nI['author'];
$mainobjective = $nI['mainobjective'];
$contents = $nI['contents'];
$keywords = $nI['keywords'];
and then i have my html where with the use of echo i place every variable in the div i want.
It sounds like the problem you are describing is more with your PHP code, that you haven't posted, than your MySQL. Don't read them separately. Use a single query to get all 3 and then iterate through them separately with PHP.
You can use the query you already had:
$result = $myDb->query('SELECT * FROM news ORDER BY id DESC LIMIT 0,3');
Make sure you are placing the results in separate containers in PHP:
foreach($result as $row)
{
echo "<div>".$row."</div>";
}
I'm having trouble getting this to work correctly on my classifieds website, but basically what I am doing is taking all from an Item table LIMIT 40 and displaying it on page. Now for the hard part, I am taking all from a category table, which contains the names of the categories (each category name has a relative id). I need to print out the name of the category WHEN its id is equal to the id of the item. Hopefully the code will help clarify:
$sql = mysql_query("SELECT * FROM table_item ORDER BY creationtime DESC LIMIT 40");
$sql2 = mysql_query("SELECT * FROM table_category");
$ad_count = mysql_num_rows($sql);
$row2 = mysql_fetch_array($sql2);
if($ad_count > 0){
while($row = mysql_fetch_array($sql)){
$item_categoryId = $row["cid"];
$categoryId = $row2["id"];
$categoryName = $row2["name"];
while($item_categoryId == $categoryId){
$catName = $categoryName;
}
echo $catName;
}
}
Now, there is a little more to the code then what I put up, I tried to keep this short and sweet. Instead of echoing the category name, its actually being put into an HTML table row and there is also a lot more information being put in as well. Everything works fine when I don't do anything with the category name, but when I try to build something to access and compare it, then everything goes to shit.
Also, I should mention that this nested while loop seemed to be the best way to go about this (I have tried many ways) and the error I am getting for this is that "there is an unexpected '}'".
Use joins instead of nested loops:
SELECT
*
FROM
table_item,
INNER JOIN
table_category
ON
table_item.cid=table_category.id
ORDER BY
creationtime DESC
LIMIT 40
If not every item has a corresponding category, use LEFT JOIN instead of INNER JOIN.