I created a PHP file to populate a page, using AJAX, but I can't find a solution to my problem.
Here's my PHP and its Outputs:
$result = mysql_query("SELECT id, product, picture FROM table1 ORDER BY id DESC");
$products = array();
while($product = mysql_fetch_array($result, MYSQL_ASSOC)) {
$products[] = ($product);
}
$json = json_encode($products);
$output = isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;
echo $output;
This will print:
[{"id":"5","product":"product5","picture":"picture5.jpg"},
{"id":"4","product":"product4","picture":"picture4.jpg"},
{"id":"3","product":"product3","picture":"picture3.jpg"},
{"id":"2","product":"product2","picture":"picture2.jpg"},
{"id":"1","product":"product1","picture":"picture1.jpg"}]
I want to add the field "In_Stock" on this Output using a another query to output something like this:
[{"id":"5","product":"product5","picture":"picture5.jpg","in_stock":"yes"},
{"id":"4","product":"product4","picture":"picture4.jpg","in_stock":"no"},
{"id":"3","product":"product3","picture":"picture3.jpg","in_stock":"yes"},
{"id":"2","product":"product2","picture":"picture2.jpg","in_stock":"yes"},
{"id":"1","product":"product1","picture":"picture1.jpg","in_stock":"no"}]
My question is: Its possible to use the value of the array (Inside the first While) to do a search in another table, add this value to products array and keep the same "layout" on the output above?
EDIT:
These are my tables:
TABLE1
id
product
picture
And the second one
TABLE2
id
user
product_id
in_stock
The same product may have different stocks depending on the User...
Yes, you could do another query, but it probably makes more sense to just alter the first query to include all the data you need, which would look something like this:
mysql_query("SELECT table1.id, table1.product, table1.picture, table2.in_stock
FROM table1
LEFT JOIN table2 ON (table1.id = table2.product_id
AND table2.user = " . intval($_SESSION['user']) . ")
ORDER BY table1.id DESC");
Edit: Added in the user from session per your comment. I used intval because I am assuming you are using an integer for the id of the user, and I don't know how the $_SESSION value got set - if it is from user input then it should be escaped.
As a side note, mysql_query is deprecated, you should look into mysqli and prepared statements.
Related
I have updated my original post based on what I learned from your comments below. It is a much simpler process than I originally thought.
require '../database.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Orders WHERE id = 430";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
echo 'Order Num: ' . $data['id'] . '<br>';
$sql = "SELECT * FROM Order_items
JOIN Parts ON Parts.id = Order_Items.part_id
WHERE Order_Items.orders_id = 430";
$q = $pdo->prepare($sql);
$q->execute(array($line_item_id));
$data = $q->fetch(PDO::FETCH_ASSOC);
while ($data = $q->fetch(PDO::FETCH_ASSOC))
{
echo '- ' . $data['part_num'] . $data['qty'] . "<br>";
}
Database::disconnect();
Unfortunately, only my first query is producing results. The second query is producing the following ERROR LOG: "Base table or view not found: 1146 Table 'Order_items' doesn't exist" but I am expecting the following results.
Expected Results from Query 1:
Order Num: 430
Expected Results from Query 2:
- Screws 400
- Plates 35
- Clips 37
- Poles 7
- Zip ties 45
Now that I understand where you are coming from, let's explain a couple of things.
1.PDO and mysqli are two ways of accessing the database; they essentially do the same things, but the notation is different.
2.Arrays are variables with multiple "compartments". Most typical array has the compartments identified by a numerical index, like:
$array[0] = 'OR12345'; //order number
$array[1] = '2017-03-15'; //order date
$array[2] = 23; //id of a person/customer placing the order
etc. But this would require us to remember which number index means what. So in PHP there are associative arrays, which allow using text strings as indexes, and are used for fetching SQL query results.
3.The statement
$data = $q->fetch(PDO::FETCH_ASSOC)
or
$row = $result->fetch_assoc()
do exactly the same thing: put a record (row) from a query into an array, using field names as indexes. This way it's easy to use the data, because you can use field names (with a little bit around them) for displaying or manipulating the field values.
4.The
while ($row = $result->fetch_assoc())
does two things. It checks if there is a row still to fetch from the query results. and while there is one - it puts it into the array $row for you to use, and repeats (all the stuff between { and }).
So you fetch the row, display the results in whatever form you want, and then loop to fetch another row. If there are no more rows to fetch - the loop ends.
5.You should avoid using commas in the FROM clause in a query. This notation can be used only if the fields joining the tables are obvious (named the same), but it is bad practice anyway. The joins between tables should be specified explicitly. In the first query you want the header only, and there is no additional table needed in your example, so you should have just
SELECT *
FROM Orders
WHERE Orders.Order_ID = 12345
whereas in the second query I understand you have a table Parts, which contains descriptions of various parts that can be ordered? If so, then the second query should have:
SELECT *
FROM Order_items
JOIN Parts ON Parts.ID = Order_Items.Part_ID
WHEERE Order_Items.Order_ID = 12345
If in your Orders table you had a field for the ID of the supplier Supplier_ID, pointing to a Suppliers table, and an ID of the person placing the order Customer_ID, pointing to a Customers table, then the first query would look like this:
SELECT *
FROM Orders
JOIN Suppliers ON Suppliers.ID = Orders.Supplier_ID
JOIN Customers ON Customers.ID = Orders.Customer_ID
WHERE Orders.Order_ID = 12345
Hope this is enough for you to learn further on your own :).
I'm trying to place one mysql select inside another one and combine the results to be displayed.
this is my code:
$allattrs = "";
$sql69 = "SELECT * FROM product_details";
$query69 = mysqli_query($db_conx, $sql69);
$login_check69 = mysqli_num_rows($query69);
if($login_check69 > 0){
while($row69 = mysqli_fetch_array($query69, MYSQLI_ASSOC)){
$FID = $row69["id"];
$sql2s = "SELECT * FROM ATTRIBUTES WHERE id='$FID'";
$query2s = mysqli_query($db_conx, $sql2s);
$login_check2s = mysqli_num_rows($query2s);
if($login_check2s > 0){
while($row2s = mysqli_fetch_array($query2s, MYSQLI_ASSOC)){
// Get member ID into a session variable
$Sid = $row2s["id"];
$attr = $row2s["attr"];
$allattrs .= ''.$attr.', ';
}
}
$product_list .= '<tr>
<td>'.$allattrs.'</td>
</tr>';
}
}
The problem i'm having is that the $allattrs returns the values but it will put everthing together.
for example:
if one attr column in mysql database has apples, and another one has oranges, when i see the results of $allattrs on my PHP page i see this:
id 1 - apples
id 2 - apples, oranges
id 3 - apples, oranges, apples, oranges
etc etc
this is in fact wrong as each attribute value needs to stay true to their own id and product_details id field!
I'm not sure what I am doing wrong to cause this.
could someone please advise on this issue?
any help would be appreciated.
The right way to write your query is using JOIN, EXISTS, or IN. I think you would find this most natural:
SELECT a.id, GROUP_CONCAT(a.attr) as attrs
FROM ATTRIBUTES a
WHERE a.id IN (SELECT id FROM product_details)
GROUP BY a.id;
This replaces a bunch of your code.
Looks like you are only interested in the the attributes then try this out instead of the first sql:
SELECT * FROM ATTRIBUTES where id IN (SELECT id FROM product_details)
You need to set $allattrs to an empty string inside your first while loop, instead of only once before.
Apart from that, you should look into the following two topics: Normalization and JOINs.
Hi there I have 2 tables
|id|musicname|url|image|type
and the second table
|id|user|songslist|
inside songsids theres an array like this
1,3,5,6,8 etc ...
What Im aiming to do is select * from table1 and echo out the table1 as in an array but instead of tables two array , the actual row of table1.
So basically To take out each row that contains the id in songslist and put them all into a php array.
I have learned a lot about PHP arrays , but I'm not that good with mysql , Any Idea of how can I do that ?
EDIT
$selectmusiclist = mysql_query("SELECT * FROM music");
$songslist = array();
while ($songs = mysql_fetch_assoc($selectmusiclist)){
$songslist[] = $songs;
}
and then table 2 select:
$username="user1";
$selectuser = mysql_query("SELECT * FROM usersmusic where user=$username");
$user = mysql_fetch_assoc($selectuser);
$songslist = $user['songslist'];
NOW I need to tell the array $songslist[] to output only the songs with id $songslist contained ids
I think running a join like this will give you the results you are after.
SELECT * FROM usersmusic as um
join music as m
on um.songslist = m.id
where user = '$username'
If $username is not a static value make sure you escape it; don't want to get SQL injected in the future.
Also note the mysql_ driver is now deprecated you should consider updating to mysqli or PDO.
Whilst populating a table based on ids and labels from different tables, it appeared apparent there must potentially be a better way of achieving the same result with less code and a more direct approach using LEFT JOIN but i am puzzled after trying to work out if its actually capable of achieving the desired result.
Am i correct in thinking a LEFT JOIN is usable in this instance?
Referencing two tables against one another where one lists id's related to another table and that other table has the titles allocated for each reference?
I know full well that if theres independent information for each row LEFT JOIN is suitable, but where theres in this case only several ids to reference for many rows, i just am not clicking with how i could get it to work...
The current way i am achieving my desired result in PHP/MySQL
$itemid = $row['item_id'];
$secid = mysql_query(" SELECT * FROM item_groups WHERE item_id='$itemid' ");
while ($secidrow = mysql_fetch_assoc($secid)) {
//echo $secidrow["section_id"]; //testing
$id = $secidrow["section_id"];
$secnameget = mysql_query(" SELECT * FROM items_section_list WHERE item_sec_id='$id' ");
while ($secname = mysql_fetch_assoc($secnameget)) {
echo $secname["section_name"];
}
}
Example of the data
Item groups
:drink
:food
:shelf
Item List
itemId, groupId
Group List
groupId, groupTitle
The idea so outputting data to a table instead of outputting "Item & Id Number, in place of the ID Number the title actually appears.
I have achieved the desired result but i am always interested in seeking better ways to achieve the desired result.
If I've deciphered your code properly, you should be able to use the following query to get both values at the same time.
$itemid = $row['item_id'];
$secid = mysql_query("
SELECT *
FROM item_groups
LEFT JOIN items_section_list
ON items_section_list.item_sec_id = item_groups.section_id
WHERE item_id='$itemid'
");
while ($secidrow = mysql_fetch_assoc($secid)) {
//$id = $secidrow["section_id"];
echo $secidrow["section_name"];
}
I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work