PHP PDO: SELECT array within IN() - php

I am a little late to the game and am trying to transition to PDO from mysql_* while trying to tackle a current challenge. I have an interface where I capture box number values within an array and that array is stored in another array by line item (for clarity purposes these are nested arrays).
My main purpose is to take the box numbers for a particular line item and run a mysql select query to return the number of units in that given set of boxes. If the qty in the boxes is not the quantity the user thinks there are I want it to throw an error.
Currently my challenge is I'm getting an empty result set. I believe this to be due to my array of box numbers not being properly passed to the PDO select statement. Any thoughts or guidance would be much appreciated.
Here is what I have so far:
$Boxes = $_POST['Boxes']; //this includes box numbers within an array for each line item of a form
$e = 0;
while($e<$num1){
$units = 0;
$r = 0;
$SO_Line_Item=mysql_result($result1,$e,"SO_Line_Item");
foreach ($Boxes[$e] as $a => $b) // the purpose of this loop is to take the values from Boxes and store it in $zzz which I hope to use in my Select statement below.
{
$zzz[] = $Boxes[$e][$r];
$r++;
}
//end inner foreach
$BNs= implode(',', $zzz);
$db = new PDO('mysql:host=XXXXXX ;dbname=XXXXXX', $dbuser,$dbpass);
$stmt = $db->prepare("SELECT Box_Num,Timestamp,SN,Assy_Status FROM Current_Box WHERE Box_Num IN(' . $BNs . ')");
$stmt->execute($zzz);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($results); // this shows up as an empty array
}
$e++;
}

This got it done. Thanks to Marc B for his thoughts:
$e = 0;
while($e<$num1){
$units = 0;
$r = 0;
$SO_Line_Item=mysql_result($result1,$e,"SO_Line_Item");
foreach ($Boxes[$e] as $a => $b)
{
$zzz[] = $Boxes[$e][$r];
$ce = count($Boxes[$e]);
$r++;
}
//end inner foreach
$products = implode(',', array_fill(0,$ce, '?'));
$db = new PDO('mysql:host=192.168.1.197 ;dbname=Tracking', $dbuser,$dbpass);
$stmt = $db->prepare("SELECT Box_Num,Timestamp,E3_SN,Assy_Status FROM Current_Box WHERE Box_Num IN( $products )");
$stmt->execute($zzz);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($zzz);
$e++;
}

Related

How to check array for existing elements to assign ticket numbers?

I am attempting to create a function which will tell me what free numbers are available to use, I have a function which returns the numbers which have already been taken in an array.
I wish to check the returned array with existing elements against a blank array, and if the number is not in the array then push/add it to the empty array to allow me to return an array of available numbers/tickets.
I have tried some examples on here and looked upon PHP documentation on some items trying array_intersect, in_array etc.
I believe the best way to add the free numbers to the empty array is using array_push which has not been implemented into the example code as of yet.
Available numbers function so far:
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
for($i = 1; $i<$maxTickets; $i++){
$x = $i-1;
foreach($takenNumbers as $v){
if(in_array($v, $freeNumbers)){
echo "Element is in array";
break;
} else {
echo $v . "is taken";
}
}
}
//return $freeNumbers;
}
Taken numbers function
function takenNumbers($drawID){
$connect = new mysqli("localhost", "root", "", "dream");
$stmt = $connect->prepare("SELECT * FROM transaction WHERE DrawID = ?");
$stmt->bind_param("i", $drawID);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 0) exit("No rows");
$tickets = array();
while($row = $result->fetch_assoc()){
$id = $row['ID'];
$tickets[] = $row['TicketNumber'];
}
return $tickets;
}
Max tickets is just counting from a database transaction table to count already assigned numbers.
In this current iteration of the project, I am receiving the following "1 is taken" for each loop.
Thanks in advance, I have attempted to explain what I am attempting to do in best terms possible. But if I haven't been able to describe something please reply so I can explain it further.
Instead of checking on each array item, you could get the the difference values between all of the ticket numbers and the taken ticket numbers array using array_diff() :
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
$allTickets = range(1, $maxTickets);
$freeNumbers = array_values(array_diff($allTickets, $takenNumbers));
//return $freeNumbers;
}
Edit : added array_values() to reset the array index returned from the array_diff() function.
Edit : Or if you prefer to use the array_push() function, you could do it like :
for($i = 1; $i<$maxTickets; $i++){
if(!in_array($i, $takenNumbers)){
array_push($freeNumbers, $i);
}
}

MSSQL returns multiple rows into array, explode into one array per row

I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}

PHP assign result from nested query into array

I need help in order to assign the results of a nested query into array. This is the scenario:
$Date_Collection = mysql_query("SELECT DISTINCT Date FROM TblDate");
while($date = mysql_fetch_array($Date_Collection)) // Loop through all the dates
{
$var_date = $date['Date'];
$result = mysql_query("select min(Speed) as Min_spd, max (Speed) as Max_spd, avg
(Speed) as Avg_spd from ... where Date= $var_date");
while($row = mysql_fetch_array($result))
{
echo "row[Min_spd]";
echo "row[Max_spd]";
echo "row[Avg_spd]";
}
}
The output from this query is like this:
Min_Spd |Max_Spd |Avg_Spd| Date|
12.0| 25.0| 20.4| 2012-10-01|
11.0| 28.0| 21.4| 2012-10-02|
10.0| 26.0| 23.4| 2012-10-05|
08.0| 22.0| 21.4| 2012-10-08|
I basically need to show the sum of Min_Spd, Sum of Max_spd, Sum of Avg_spd for all these dates. So, I thought that If I can assign these values into an array and later compute these sum from the array, it might be a good idea.
Can anyone please help me regarding this? Can I use an array to store the values and later access these values and calculate the sum of these values. If I can use an array, could anyone please show me the syntax of using array in PHP. I would really appreciate any help regarding this.
Is there any alternative way rather than using an array, such as creating a temporary table to save these values and later delete the temporary table. If a temporary table can be used, could you please show me how to do that. I could use the temptable for a single loop, but there is a nested loop and I don't exactly know what to do to create a temp table inside the nested loop to store all the values.
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
then later on you can do
foreach($data as $row) {
echo $row['Min_spd'];
echo ...
...
}
I don't know if the MySQL SUM function can be used to do that on te query, try it. But on this example, using arrays you should store the values and then use array_sum to return the sum of the elements. Something like this:
$min_spd = array();
$max_spd = array();
$avg_spd = array();
while($row = mysql_fetch_assoc($result))
{
$min_spd[] = $row['Min_spd'];
$max_spd[] = $row['Max_spd'];
$avg_spd[] = $row['Avg_spd'];
}
echo array_sum($min_spd);
It can also be done using variables to store and add the values:
$min_spd = 0;
$max_spd = 0;
$avg_spd = 0;
while($row = mysql_fetch_assoc($result))
{
$min_spd += $row['Min_spd'];
$max_spd += $row['Max_spd'];
$avg_spd += $row['Avg_spd'];
}
echo $min_spd;
I would first of all save yourself a nested query by doing the first query as:
$result = mysql_query("select Date, min(Speed) as Min_spd, max (Speed) as Max_spd, avg(Speed) as Avg_spd from ... group by Date")
And then create a running total for the sums as you're looping through each row:
$sumMinSpeeds=0;
$sumMaxSpeeds=0;
$sumAvgSpeeds=0;
while($row = mysql_fetch_array($result))
{
echo row['Min_spd'];
echo row['Max_spd'];
echo row['Avg_spd'];
$sumMinSpeeds += $row['Min_spd'];
$sumMinSpeeds += $row['Max_spd'];
$sumMinSpeeds += $row['Avg_spd'];
}
echo $sumMinSpeeds;
echo $sumMaxSpeeds;
echo $sumAvgSpeeds;
Instead of doing several MySQL queries in a loop, consider constructing such a query, which will return all the results you need.
SQL
First of all, it would make sense to use the GROUP SQL construct.
SELECT
s.Date date,
MIN(s.Speed) min,
MAX(s.Speed) max,
AVG(s.Speed) avg
FROM speed_table s
WHERE s.Date IN (SELECT DISTINCT d.Date FROM date_table d)
GROUP BY s.Date
It is important to understand what each part of this query does. If you run into any problems, consult the MySQL reference manual.
PHP
Forget about using mysql_* functions: they are deprecated and better implementations have emerged: PDO and mysqli. My example uses PDO.
try {
$dbh = new \PDO('mysql:dbname=my_db_name;host=127.0.0.1', 'dbuser', 'dbpass');
} catch (\PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = '...'; // This is the query
$stmt = $pdo->prepare($sql);
$stmt->execute();
You can now either iterate over the returned result set
while ($row = $stmt->fetch()) {
printf("%s; %s; %s; %s\n", $row['date'], $row['min'], $row['max'], $row['avg']);
}
or have the Statement object return the whole array by using
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);

Return a multidimensional array from MySQL result php

I have a PHP function that extract dat of an invoice from DB.
The invoice may have more then one line (one product).
function getInvoiceLines($id)
{
$res = mysql_query("select * from invoice_lines where id = $id ");
while ($row = mysql_fetch_array($res))
{
$res_retun['ref']=$row['ref'];
$res_retun['label']=$row['label'];
$res_retun['price']=$row['label'];
$res_retun['qty']=$row['qty'];
}
return $res_retun ;
}
I found this link Create a Multidimensional Array with PHP and MySQL and I made this code using that concept.
Now, how can I move something like a cursor to the next line and add more lines if there's more in MySQL result??
If it's possible, how can I do to show data in HTML with for ??
A little modification should get what you want, below the [] operator is a shorthand notation to add elements to an array, the problem with your code is that you are overwriting the same keys on each iteration
// fetch only what you need;
$res = mysql_query("select ref, label, price, qty from invoice_lines where id = $id ");
while ($row = mysql_fetch_array($res))
{
$res_return[] = $row;
}
return $res_return;
Note, I fixed some of your typos (you were using $rw instead of $row in the loop of your original code)
If you used PDO with fetchAll() you would be returned with the array your expecting, also be safe from nastys:
<?php //Cut down
$db = new PDO("mysql:host=localhost;dbname=dbName", 'root', 'pass');
$sql = "SELECT * FROM invoice_lines WHERE id = :id ";
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$res_return = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
Then you just loop through the array like with any other array:
<?php
foreach($res_return as $row){
echo $row['ref'];
...
...
}
?>
Also id should not have more then 1 row it should be unique IF its your primary key.
If you were using PDO like you should be it would be super easy and you would solve your sql injection issues
$db = new PDO(...);
function getInvoiceLines( $db, $id )
{
$stmnt = $db->prepare("select ref, label, price, qty from invoice_lines where id=?");
$stmnt->execute( array( $id ) );
return $stmnt->fetchAll( PDO::FETCH_ASSOC );
}
Make variable global first Then access it in function. For exp.
$return_arr = array(); // outside function
$i = 0;
cal_recursive(); // call function first time
function cal_recursive(){
global $return_arr;
global $i;
$return_arr[$i] = // here push value to array variable
$i++;
// do code for recursive function
return $return_arr // after end
}

Working with arrays in Kohana, Blank page?

tl;dr - Pushing an array (by $array[] or $array[$id] is not working in Kohana 3, it gives a blank white page.
I'm using Kohana (3), it's my first experience with MVC and it's been great so far; however, I'm working with a database and encountered a weird problem that I was hoping someone could shed some light on:
My workflow is like this, to give you an idea of my problems surrounding:
$sql = "SELECT table1.row1, max(table2.row1) as `maxAwesome` FROM table1, table2 WHERE table1.id=table2.table1id GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
foreach ($table1Results as $result1)
{
$sql = "SELECT * FROM table2 WHERE table2id='" . $result1['id'] . "' AND column > 21";
$table2Results = DB::query(Database::SELECT, $sql)->execute();
$subArray = array();
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
I do a query where I run a couple max/min functions then do a query within the foreach doing another select to build a master array of data formatted the way I want it and all the SQL etc works fine and dandy; however, the problem arises when I'm pushing the array.
It seems whenever I push the array by doing either $array[] = array("data"); or by specifying the key $array[$id] = array("data"); Kohana gives me a straight blank page, no error, no output etc.
Sometimes I get a Kohana error indicating the key does not exist (duh, I'm creating it) but for the most part the output is straight white.
Why is this happening? Am I going about it wrong?
Thanks in advance.
Clarity edit:
My SQL blunders aside, the issue lies in the building of the secondary array, for example:
$queryStores = "SELECT stores.store_id, stores.title, max(product.discount) as `max_discount`, min(product.discount) as `min_discount`
FROM stores, products
WHERE products.store=stores.store_id
GROUP BY products.store";
$stores = DB::Query(Database::SELECT, $queryStores)->execute();
$formattedStores = array();
if (count($stores))
{
foreach ($stores as $store)
{
$formattedStores[$store['store_id']] = array(
"title" => $store['title'],
);
// Same result if just doing $formattedStores[] = array();
// Problem goes away should I do:
// $formattedStores = array("This works");
//
}
}
echo "<pre>";
print_r($formattedStores);
echo "</pre>";
That does not print an array, it simply gives a blank page; however, if i change it to just re-set the $formattedStores array to something I get an output. What is it about pushing the array that's causing a problem, perhaps a Kohana bug?
Thanks
Your code should be like:-
$sql = "SELECT table1.id, table1.row1, max(table2.row1) as `maxAwesome`
FROM table1, table2
WHERE table1.id = table2.table1id
GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
if (count($table1Results))
{
foreach ($table1Results as $result1)
{
$sqlInner = "SELECT * FROM table2
WHERE table2id = '" . $result1['id'] . "'
AND column > 21";
$table2Results = DB::query(Database::SELECT, $sqlInner)->execute();
$subArray = array();
if (count($table2Results))
{
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
}
Some valuable coding standards & miss-ups:-
You have got the "id" field (w.r.t. the "table1" DB table) missing from the first SQL.
The second SQL should be better written using another variable naming, so as to keep it separate from the first one. Hence the second variable is named as "$sqlInner".
It's always better to check for any existence of array elements in an array variable, so I have used the simple checks using the "if" statement.
Hope it helps.
I've determined this to be memory related.

Categories