Getting only first entry php mysql - php

I have an mysqli table having values as such:-
id | price
65| 7000
67| 7001
And a php code to echo both out using an array variable:-
require('setup.php'); // got connection
$array = array(0 => 65, 1 => 67);
$d = implode("," , $array);
$sql = "SELECT price FROM trade WHERE id IN('$d')";
$query = mysqli_query($conn, $sql);
if($query){
while ($row = mysqli_fetch_array($query)) {
echo $row['price'].'<br>';
}
}
else {
echo mysqli_error($conn);
}
The output should come as
7000
7001
but it's only 7000.

You need to do IN(65,67) while you are doing IN('65,67')
So remove ' around $d
Code needs to be:-
$sql = "SELECT price FROM trade WHERE id IN($d)";
Note:- use fetch_assoc() for lighter array iteration (as it only gives associative array resultset)
while ($row = mysqli_fetch_assoc($query)) {
Working snippet :- http://rextester.com/FEFBWZ40805

Remove extra single quotes in IN() tag.
Corrected code:
$sql = "SELECT price FROM trade WHERE id IN($d)";
$sql Outputs:
SELECT price FROM trade WHERE id IN(65,67)
You can check the code here:

Edit your query as below,
$sql = "SELECT price FROM trade WHERE id IN($d)";
Hope this helps.

Passing $d withing quotes makes the IN('65,66') look like this during execution so you need to remove that as by the default convention you just need to pass an array. So change your query to:
SELECT price FROM trade WHERE id IN($d)

Please check your SQL query
$sql = "SELECT price FROM trade WHERE id IN('$d')";
Please change this query like below:
$sql = "SELECT price FROM trade WHERE id IN($d)";
You should not use single quote with php varible.

Try something like this:
require('setup.php');
$array = [65, 67];
$d = implode(',', $array);
$sql = "SELECT price FROM trade WHERE id IN($d)";
$query = mysqli_query($conn, $sql);
if($query){
while ($row = mysqli_fetch_assoc($query)) {
echo $row['price'].'<br>';
}
}
else {
echo mysqli_error($conn);
}

Related

Get results and use them to another query mysql php

How can I use the fetched result to use the values to make another query? I tried to find info on php.net, but can`t figure out.
$sql = "SELECT id FROM orders WHERE customer_id=$customer_id";
$query = mysqli_query($conn, $sql);
while($row= mysqli_fetch_array($query)) {
$ordersid=$row['id'];
}
$ordersid returns: 13 - order number 1 and 3.
Here is my difficulty. How can I make $orderid(1,3)?
After that I want to use 1 and 3 like that in another query:
SELECT * FROM orderdetails WHERE order_id IN ($orderid)
In that way without direct relation will have all answers from the first query to second.
Where is my mistake?
You could put the results into an array and use like follows:
$a = array();
$sql = "SELECT id FROM orders WHERE customer_id=$customer_id";
$query = mysqli_query($conn, $sql);
while($row= mysqli_fetch_array($query)) {
array_push($a, $row['id']);
}
$data = implode("', '", $a);
And in your next query like so:
SELECT * FROM orderdetails WHERE order_id IN ('$data')

MYSQL query using a set of values (values stored from a session array) not working

I'm just a beginner and I'm doing a project (a shopping cart). User can add a product to the cart and the id of the product stores in a session. When I use those ids to echo out PRICE from DB it's not working. I'm using PHP & MYSQL. Here is my code
if(count($_SESSION['cart_items'])>0){
// getting the product ids
$nos = "";
foreach($_SESSION['cart_items'] as $no=>$value){
$nos = $nos . $no . ",";
}
// removing the last comma
$nos = rtrim($nos, ',');
//echo $nos; (will display like this INT VALUES 1,2,3,4)
$nos=mysql_real_escape_string($nos);
$site4->DBlogin();
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
$result = mysql_query($qry);
$row = mysql_fetch_assoc($result);
echo $row['price'];
}
PHP is not recursively embeddable:
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
^---start of string end of string ---^
Since you're already in a string, .implode(...) is just plain text, NOT executable code.
This means your query is illegal/invalid SQL, and if you had even basic/minimal error checking, would have been told about this:
$result = mysql_query($qry) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
I have fixed the issue and thanx MARC for your suggestions.
I was making two mistakes:- IMPLODE input field was not an array. and as Marc said the query was not executable.
Changes made :-
$nos = rtrim($nos, ',');
**$narray = array($nos);**
$fgmembersite4->DBlogin();
$qry = **'SELECT * FROM vendorproducts WHERE product_no IN ('.implode(',',$narray).')'**;
$result = mysql_query($qry) or die(mysql_error());
**while (**$row = mysql_fetch_assoc($result)){
echo $row['price'];}

Mysqli count not working properly

$sql = "SELECT count(id),soft_name from table_name GROUP BY soft_name";
$d = mysqli_fetch_assoc(mysqli_query($db_name, $sql));
$c = array_shift($d);
The result is always 2, but the database contains more than 3000 items. What could be the problem?
Records are not pulled the way you are pulling for that you have to use similar to following code:
if($result = mysqli_query($db_name, $sql)){
while($d = mysqli_fetch_assoc($result){
echo $d['count'];
}
}
More reference here.

How to UPDATE all rows in SQL with one query?

I have an existing DATABASE of Prestashop, and I have made small modifications to it. I made a separate PHP page which gets data from table with products (only the data i need) and shows me all products that ARE IN THAT TABLE, one after another. I also have a function which updates a products, on which i press EDIT.
So, in a simple words i can update a single product per click. But now I have about 220 products, and in order to update a value (price) for each product, now, i must click EDIT for each product, 220 times.
Is there a way to make a query in order to update all rows after i click a BUTTON?
Bellow I will show you some basic parts from my script:
GET function:
<?php
$strSQL = "SELECT * FROM ps_product";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
while($objResult = mysql_fetch_array($objQuery))
{
?>
<!-- HTML CODE -->
<? } ?>
UPDATE function for each product
if($_POST["hdnCmd"] == "Update")
{
$strSQL = "UPDATE ps_product_shop SET ";
$strSQL .="id_product = '".$_POST["txtEditid_product"]."' ";
$strSQL .=",price = '".$_POST["txtEditprice"]."' ";
$strSQL .=",active = '".$_POST["txtEditactive"]."' ";
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "Error Update [".mysql_error()."]";
}
}
$_POST["hdnEditid_product] is the product id value that is taken from table.
Please help me to understand how to make a similar **UPDATE function** **which will update all rows (product_id) at once?
As an example i must work around this code:
if($_POST["UPDATEALLPRODUCTS"] == "Update")
{
$strSQL = "UPDATE ps_product_shop SET ";
$strSQL .=",price = '".$_POST["txtEditprice"]."' ";
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "Error Update [".mysql_error()."]";
}
}
but what I must add/change here:
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
To update all rows to the same value run this query
UPDATE ps_product_shop SET price='".$_POST["txtEditprice"]."';
NOTE: Every records in ps_products_shop will get the same value in price.
How about this ?
Make an array like this : id => price, and then :
$prices = array(
1=>300,
5=>180,
...
);
foreach ($prices as $id => $price) {
$query = "UPDATE ps_product_shop SET price='".$price."' WHERE
id_product='".$id."' ";
mysql_query($query);
}
One way to do it, if you insist on using a single query:
<?php
$product_updates = array("1" => "500", "2" => "1299.99");
$sql_query = "UPDATE my_database.products SET price = CASE id ";
foreach ($product_updates as $key => $value) {
$sql_query .= "WHEN '$key' THEN '$value' ";
}
$sql_query .= "END;";
mysql_query($sql_query);
?>
I am assuming that the page already has the updated price / info that you need and therefore it is just plucking the php variables out
UPDATE ps_product_shop SET price
= CASE
WHEN id_product= $id_product_1
THEN '$edited_price_1'
WHEN id_product = $id_product_2
THEN '$edited_price_2'
Without seeing the form structure it is hard to see what would be the correct variable names but hopefully you can take the code and go with it, i have to do something similar and have PhP autobuild the query using this method

PHP not displaying data

Any ideas why this simple php code won't display results when trying to echo the data.
<?php
{
mysql_connect("localhost" , "" , "") or die (mysql_error());
mysql_select_db("") or die(mysql_error());
$pid=intval($_SESSION["User_id"]);
$query = "SELECT `car`, `details`, `price` FROM `Car``";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
while($row=mysql_fetch_assoc($result))
{
$_SESSION['car'] = $row['car'];
$_SESSION['details'] = $row['details'];
$_SESSION['price'] = $row['price'];
}
}
?>
<?php echo $_SESSION['car']; ?>
<?php echo $_SESSION['details']; ?>
<?php echo $_SESSION['price']; ?>
Just testing at the moment to see if the car, price and details display from the database and they don't seem to.
You missed session_start(); at start of page and change
$query = "SELECT `car`, `details`, `price` FROM `Car``";
^
to
$query = "SELECT `car`, `details`, `price` FROM `Car`";
Are you expecting one or many results for this query ?
If many results, you are saving the last entry in the session.
If only one, just do : $row=mysql_fetch_assoc($result) instead of this while.
Check the query.Try to echo it, copy, paste in MySQL and run it. But you have $pid, have you put it in the query?
$query = "SELECT car, details, price FROM Car WHERE id = $pid ";
I rather remove all backticks since non of those identifiers are reserved keywords.
$query = "SELECT car, details, price FROM Car";

Categories