So I have an associative array $_SESSION['cart_items']) This is the current output when I print_r($_SESSION['cart_items']):
Array
(
[3] => 23
[5] => 5
[4] => 1
)
In the output above, the first one for example [3]=>23 where [3] is the id and 23 is the quantity I entered from a form:
My current data:
Note that in the image above, the quantity column is different from the quantity I'm entering from a form.
So far this is the code I've tried:
$statement = $conn->query("SELECT id, name, price, quantity FROM product WHERE id IN (".implode(',',$_SESSION['cart_items']).")");
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
And this is the output:
[{"id":"5","name":"ballpen","price":"23","quantity":"13"}]
As you can see it works, though I only get a single row which should be three.
Is there something wrong with my query?
You show that the array keys in the session array match the ids in the database. implode() implodes/joins the values in the array. So you need to implode the keys:
implode(',', array_keys($_SESSION['cart_items']))
Or flip the array:
implode(',', array_flip($_SESSION['cart_items']))
Related
This question already has answers here:
Find duplicate records in MySQL
(28 answers)
Closed 4 years ago.
Im trying to search for duplicate records inside an array...
Easy enough ....
However I only want it to return values that are duplicates..
I dont want it to display the entire array values with the count ( there are over 400 million entries )
Here is the code I have tried ( it works in printing all values but not what I want )
$query = mysqli_query($dbc, "SELECT * FROM `barcodes`");
while ($row = mysqli_fetch_row($query))
{
$result_array[] = $row[16];
}
print_r(array_count_values($result_array));
If anyone can help me it would really be appreciated as I've searched google and SO for over an hour and a half and not found what I want
Sample Of Array Print
[502185864797] => 1
[502185864798] => 1
[502185864799] => 1
[502185864800] => 1
[502185864801] => 2
[502185864802] => 2
[502185864803] => 2
[502185864804] => 2
[502185864805] => 2
[502185864806] => 2
I only want values that have a count > 1 displayed
Depending on what you want displayed (for example this just gives the ID of a row) it would be better to try it in SQL...
SELECT ID
FROM `barcodes`
GROUP BY ID
HAVING count(ID)>1
The idea is to just retrieve ID's where the count value is more than one.
So this could look like...
$query = mysqli_query($dbc, "SELECT barcode
FROM `barcodes`
GROUP BY barcode
HAVING count(barcode)>1");
$result_array = mysqli_fetch_all($query, MYSQLI_ASSOC);
print_r($result_array);
If you wanted to have the number of times it exists, just add the count to the SELECT list...
SELECT ID, count(ID) times
FROM `barcodes`
GROUP BY ID
HAVING count(ID)>1
Use array_count_values to get the count of each value.
Then use array_diff to filter out all unique values.
Array_keys get the value that array_count_values place in the keys.
$counts = array_count_values($arr);
$dupes = array_keys(array_diff($counts, [1]));
Edit after seeing the array:
$dupes = array_keys(array_diff($arr, [1]));
Is all you need. The array already shows the count of value (key).
i guess array_unique will do your work. Its a inbuilt function of php which removes all duplicates values from the array.
if you are intended to use only duplicates value then you can use another inbuilt function array_diff using both the arrays.
I have a database structure that looks like the following:
I am trying to store the prices as a variables so that if I reference cage_linear_feet it will display 225.
I have tried the following code:
$sql = "SELECT * from pricing WHERE region = '$region' ";
$result = mysqli_query($conn, $sql);
while($rows=mysqli_fetch_assoc($result)){
$test[] = array($rows['field']=>$rows['price']);
}
print_r ($test);
This displays the following:
Array ( [0] => Array ( [cage_linear_feet] => 225 ) [1] => Array ( [cage_doors] => 1800 ) )
How do I access the "225" and "1800" values ensuring that if more records are added to the db it will still pick up the correct records. E.g as the $test1 which is cage_doors may change if records are added.
My opinion is that there is no point in wrapping the key-value pairs in their own separate arrays. I would change this line:
$test[] = array($rows['field']=>$rows['price']);
to this:
$test[$rows['field']] = $rows['price'];
The data association will be maintained in the key=>value pairs of one associative array ($test). So echo $test['cage_linear_feet'] ---> 225
If you want to set field as the array-key
$sql = "SELECT * from pricing WHERE region = '$region' ";
$result = mysqli_query($conn, $sql);
while($rows=mysqli_fetch_assoc($result)){
$test[$rows['field']] = $rows['price']);
}
print_r ($test);
No you should be able to reference by field like so:
echo $test['cage_doors'];
// returns 1800
Is the column 'field' unique? If so, do this:
while($rows=mysqli_fetch_assoc($result)){
$test[$rows['field']] = $rows['price'];
}
This will set the key in the array to the field, i.e.
Array('cage_doors' => 1800)
If its not unique, I recommend doing something like:
while($rows=mysqli_fetch_assoc($result)){
$test[$rows['field'] . '_' . $rows['pricing_id']] = $rows['price'];
}
This will set the key in the array to the field and the pricing id, which makes it unique, i.e.
Array('cage_doors_2' => 1800)
thank you for reading.
I'm having a little problem with the next sentence:
$nats = mysql_query("SELECT id,name FROM reportSatus WHERE reportId = ". $_POST['id']);
$rnat = mysql_fetch_array($nats);
With print_r($rnat) :
Array(
[0] => 1
[id] => 1
[1] => Poca contaminacion
[name] => Poca contaminacion
[2] => 1
[reportId] => 1)
But in the database with the same sentence is:
id name
1 Poca contaminacion
2 Mucha contaminacion
Any idea what can it be? Thank you in advance ~
try :
echo '<table><tr><th>id</th><th>name</th></tr>';
while ($row = mysql_fetch_assoc($nats)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td></tr>";
}
echo '</table>';
From documentation
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
That's actually the way it works, if you need more rows to be returned you will need to loop throw the records
while($rnat = mysql_fetch_array($nats))
{
//print here
}
I'm trying to preg_match_all the first 12 digit number found in a mysql field, and insert that number in another field, looping through all results from the Select statement.
I have the following, which puts only the first result it finds in all the fields, so every field3 gets the same 12 digit number inserted, that 12 digit number being from the lowest unique ID field found by the Select statement. Any help with this would be greatly appreciated.
<?php
$query = mysql_query("SELECT * FROM `dbase`.`table` WHERE field1 IS NOT NULL AND field3 IS NULL");
$regexp ='/[0-9]{12}/';
while ($row = mysql_fetch_assoc($query)){
$result=($row["field1"]);
preg_match_all($regexp,$result,$matches,PREG_PATTERN_ORDER);
foreach($matches[0] as $match => $where){
$id=($row["field2"]);
$sql="UPDATE `dbase `.`table ` set field3 = $where WHERE field2 = '$id'";
mysql_query($sql);
}
}
?>
I added
print_r( $matches );
and the output was an array with one result, the number being place in all the fields:
Array
(
[0] => Array
(
[0] => 290970571788
)
)
The curly bracket change fixed the print_r output to show the the list of 12 digit numbers in this format (only first two are shown):
Array
(
[0] => Array
(
[0] => 151104658286
)
)
Array
(
[0] => Array
(
[0] => 271249191324
)
)
Thanks for that.
Utilizing the answers and suggestions given here, I've edited the code to show the final working version. The last big issue was getting the 2nd select statement to use the array result, properly looping and inserting each value in the proper row. Also cleaned up the 1st select statement and changed from preg_set_order to preg_pattern_order.
It shouldn't be
{while ($row = mysql_fetch_assoc($query))
}
but
while ($row = mysql_fetch_assoc($query)) {
}
You don't want to create code block with while statement but you want to provide code block for it.
And also you're using same WHERE condition in SELECT and UPDATE so it'll update all selected rows with same value (all will match that condition).
I have a sql statement that returns a number of records each having 10 attributes. How can i get the data and put it into a 2D array. Currently Im doing this :
while($row1 = mysql_fetch_array($result1))
{
echo $row1[0][1]; //There is an error here
}
Is $row1 a 2D array? (It should be because Im getting n*m results). If $row1 is a 2d array then shouldn't i be able to access $row[0][1]?
mysql_fetch array returns a 1-D array, combined indexed + keyed values of one single row of data from your query results. e.g. doing
SELECT field1, field2, field3 FROM sometable
and doing a mysql_fetch_array on the result will give you an array that looks like:
$row1 = array(
0 => 'value of field1',
1 => 'value of field2',
2 => 'value of field3',
'field1' => 'value of field1'
'field2' => 'value of field2',
'field3' => 'value of field3'
)
If you want to address the entire result set as a single array, you'll have to fetch each row and add it to that array first:
$data = array();
while($row1 = mysql_fetch_array($result)) {
$data[] = $row1;
}
Which would let you do $data[0][1] (2nd field [1] of 1st record [0])
From the docs:
Fetch a result row as an associative array, a numeric array, or both
If mysql_fetch_array is recovering 1 row of data, what do you expect the second dimension to be?
First off you need to verify what sort of array you are getting, then you can understand why your keys aren't valid. Try using print_r or var_dump to examine $row1.
$row1 holds only one record at a time so it is a regular one-dimension array.
If your query returns
a b c
d e f
In the first iteration of the while loop, row1 holds a b c and in the second iteration, it holds d e f, both single-dimension arrays.
$row1 is a 1-dimensional array (a single record), in your case, holding 10 values.
As the code loops through the while statement, $row1 represents each record.
refer to the documentation here: http://ca.php.net/manual/en/function.mysql-fetch-array.php