I have a shipping module I'm working to wrap up and am trying to query a mysql table, count the number of rows for a given line item on a PO, and store that result in an array. I don't think I can do group by within mysql as it will not provide a result for a line item that hasn't had any shipments against it. The intent is to take the original order quantity, count the number of units shipped against that via my query, and then subtract the units shipped from the original amount providing the remaining units to be shipped against that line item.
To ensure I receive even the zero qty for line items without shipments and to store that in the array I am trying to loop my query and store each single result as a value within my array. I'm open to suggestions on changing the approach if there is a better way.
Here is what I have for my query:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$LiShipped[] = mysql_fetch_array($query2);
$a++;
}
Unfortunately when I go to iterate through my array it appears as though nothing is stored in the array.
<?php
echo $LiShipped[0]; //results nothing
echo var_dump($LiShipped); // results array(1) { [0]=> NULL } array(2) { [0]=> NULL [1]=> NULL } array(3) { [0]=> NULL [1]=> NULL [2]=> NULL }
?>
Looks like all null values.
You need to execute the query (by calling mysql_query()) before you try and attempt to retrieve the result:
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$query2 = mysql_query( $query_2); // <-- NEED THIS
$LiShipped[] = mysql_fetch_array( $query2);
Note the above omits basic error checking and sanitation of the SQL query to prevent SQL injection.
You are not executing your query, it can't work. Try this code:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$res = mysql_query($query2);
while($LiShipped[] = mysql_fetch_array($res));
$a++;
}
Related
row[0] return giocatore’s field value
row1 return avversario’s field value
row[2] should return the values of “coins” field but it returns everytime value=0, WHY?
Here it is an image of the table, the fields and the values that row[2] is missing
Everytime I call the function coins() in a php script that I created, it always returns me the third value of the row array with value 0 (so row[2] always = 0) but when I check the value of it on php-MyAdmin using the same SQL instruction I obtain the correct values (different by 0). So why PHP is not using the right value with row[2]. The values of row[0] and row1 are always correct in php-MyAdmin and in the script results.
This is the SQL statement I created and it seems to work fine on php-MyAdmin:SELECT `giocatore`, `avversario`, `coins` FROM `tiri_dadi_table2` WHERE `contatore`= (SELECT MAX(`contatore`) FROM `tiri_dadi_table2`)
The database name: is tiri_dadi_db
The Table name is: tiri_dadi_table2
Columns names are: 'contatore' int(11), 'giocatore' int(11), 'avversario' int(11), coins int(11)
In php, as a result of the row[2] always equal to 0 I have always DB_coins = 0 at the beginning of the function in my script, so it's increased or decreased and then return to be 0 everytime.
It seems to be a scope problem but I'm not able to solve it at the moment.
Thank you in advance for your help.
(sorry for my bad english, I'm working on it! :)
function coins() {
/* Connect to the database */
$conn = new mysqli('localhost','root', '');
// Check connection
if ($conn->connect_error)
{
die("<br>Connessione fallita: " . $conn->connect_error);
}
//echo "<br>DB connesso con successo.<br>";
// Select database
mysqli_select_db($conn,"tiri_dadi_db");
// sql READING values
$sql = "SELECT `giocatore`, `avversario`, `coins` FROM `tiri_dadi_table2` WHERE `contatore`= (SELECT MAX(`contatore`) FROM `tiri_dadi_table2`)";
// on php-MyAdmin this SQL statement return me 3 correct values but here in the script, on the row[2] value there is always 0. Why??? Is a static problem or what?
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
$last_roll_R = $row[0];
$last_roll_B = $row[1];
$DB_coins = $row[2]; // ...... but this is 0 everytime even though in SQL give me the correct value...
var_dump($row); // The var_dump($row) return me something like this:
// array(3) { [0]=> string(1) "2" [1]=> string(1) "4" [2]=> string(1) "0" }
}
// free memory
mysqli_free_result($result);
}
// close connection
mysqli_close($conn);
...
}
//List of id's I want displayname for
$IDListSQL = '10,10,10,11,10,10';
//My query statement
$q = "SELECT displayname FROM accounts WHERE id IN($IDListSQL)";
//Executes query
$Res = $DB->Query($q);
//Gets all results
$Rows = $Res->fetch_all();
echo var_dump($Rows);
//Output
#->array(2)
{
[0]=> array(1)
{
[0]=> string(14) "Apple"
}
[1]=> array(1)
{
[0]=> string(10) "Orange"
}
}
The behaviour I want is an array with all the displayname's in the $IDListSQL, even if its the same ID. I also want them in the order I specified. Trying to figure this out in 1 query rather than doing up to 16 separate select queries for the purpose this is for. Any help would be appreciated kindly.
I ended up getting this done with PHP since I already had an array of ID's in the specified order. Used my same query to only get one of each ID, then joined the data into my array with the help of a couple for loops. Appreciate the help, Ctznkane525 I think what you posted would work. It sounds like it is doing the same thing I done up in PHP, trying not to use complex queries unless absolutely necessary. Speed and high ccu is critical for this app.
I'm trying to run if and else if inside a while loop in my PHP code.
The code looks like this:
<?php
$sql = "SELECT * FROM table ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$deviceType = $row["deviceType"];
if($deviceType == 'iPhone' || $deviceType == 'iPad'){
echo 'IOS';
}else if($deviceType == 'Android'){
echo 'Android';
}
}
} else {
}
?>
The code above works (sort of) but not as I was expecting it.
To give you an example, lets say I have 2 rows in MYSQL database.
like this:
id deviceType
1 Android
2 iPhone
when i run my PHP code above, I get this echo-ed on my page:
IOS
IOS
Android
Android
BUT I only have 2 rows in the database so the result should be:
IOS
Android
Could someone please advise on this issue?
This question is clearly misrepresenting your actual code/data.
When your database table has 2 rows, but you are receiving 4 rows then the onus is not on the fetching function, but on your query or database table data.
If your actual query is as posted in your question, then your table data contains more than two rows.
If your actual query is different from what you posted (say, joining the table with a copy of itself), then your data is fine and your query is failing you.
Regardless of if you are using mysqli_fetch_array($result), mysqli_fetch_array($result,MYSQLI_ASSOC), or mysqli_fetch_assoc($result), your while() loop will only do one iteration for each row of data.
The difference in resultset fetching functions:
mysqli_fetch_array($result):
array(0=>'1', 'id'=>'1', 1=>'Android', 'deviceType'=>'Android') // 1 row w/ 4 elements
array(0=>'2', 'id'=>'2', 1=>'iPhone', 'deviceType'=>'iPhone') // 1 row w/ 4 elements
mysqli_fetch_array($result,MYSQLI_ASSOC), or mysqli_fetch_assoc($result):
array('id'=>'1', 'deviceType'=>'Android') // 1 row w/ 2 elements
array('id'=>'2', 'deviceType'=>'iPhone') // 1 row w/ 2 elements
I will rewrite your code and implement some good practices:
if($result=mysqli_query($db_conx,"SELECT `deviceType` FROM `table` ORDER BY `id`;")){
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
echo ($row["deviceType"]=="Android"?"Android":"IOS"); // inline condition is a personal preference
}
}else{
echo "No rows in `table`.";
}
}
Only bother declaring a variable if you will use its value more than once (*or if it dramatically improves readability to separate it from its single use.)
So that your variable names are intuitive, name your query variable $sql or $query; and name your query's result variable $result.
Only SELECT columns that you intend to use; * is unnecessary for your case.
Backtick ` wrapping is not required on column and table names, but doing so will avoid any potential clashes with MySQL keywords.
Perform a conditional check and declare the $result variable as false or [resultset] in a single step.
Always check that $result is true before calling any functions that access the resultset. (e.g. mysqli_num_rows() and mysqli_fetch_assoc()).
if(mysqli_num_rows($result)){ will check for a non-falsey value -- I mean 0 equates to false and anything greater than 0 will be true.
Your code appears to be perfectly fine. However, instead of the expected output, you get more items than needed. If I am not mistaken, this means that you have duplicate deviceType in your database table. $productCount probably has a value of 4. You can get two values if you use this query instead:
SELECT DISTINCT `deviceType` FROM `table` ORDER BY `id`
but while this should fix the output you get, your data will still hold duplicates, so you might want to look into the data of your table and into the way it was created, find out and fix the problem.
the answer is very simple you are fetching the results twice with the while loop change this line
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
to
while($row = mysqli_fetch_assoc($query)){
then it will work right, you can see buy the order iPhone iPhone android android that is doing it twice instead of once per loop
I'm running this query, on two tables, and in first table, table tblhosting two condition must be met, WHERE tblhosting.server = tblservers.id AND tblhosting.domain = 'provided domain'. "provided domain is unique and here is complete query:
$result = mysql_query("SELECT hostname FROM tblhosting, tblservers WHERE tblhosting.server = tblservers.id AND tblhosting.domain = 'developer.infonet.hr'");
Query return correct result set, but two times, here is also var_dump output:
array(2) {
[0]=>
string(18) "lin-b15.infonet.hr"
["hostname"]=>
string(18) "lin-b15.infonet.hr"
}
Why is returning two same results, correct output is one, because domain is unique, is this because result is generate with mysq_fetch_array, so it is returning both associative array, and normal indexed array?
use
mysql_fetch_row() to Get a result row as an enumerated array
or
mysql_fetch_assoc() to Fetch a result row as an associative array
For Multiple record use it in while condition..
I'm getting this column in this bd
$result = mysql_query("SELECT short FROM textos");
and I'm trying to echo only one of the results based on the array it returns:
$col = mysql_fetch_assoc($result);
echo "<b>Short:</b>".$col[1]."<br/>";
apparently this $col array can't be accessed this way. How should it be done? Thanks
That has been already stated in comments above, so just a bit of explanation here.
mysql_fetch_assoc retrieves a result row for you presented as an associative array (an array where keys are field names and values are field values). Your query returns only one field (which is short), but still it doesn't make your row a single scalar value - it remains an array, only with a single element.
So you need to refer it as $row['short'], or in your sample $col['short'].
Bear in mind that query might return no results - you can learn that by checking if the returned value is not an array but scalar false instead, e.g.
if ($col === false) {
echo 'Error occured<br/>';
} else {
echo "<b>Short:</b>".$col['short']."<br/>";
}
Putting LIMIT into your query like again comments suggest is a good idea as well because you wouldn't be returning potentially huge amount of data when you only need one row actually. The result would still come as a multi-dimensional array though, so that part won't change.
To access the first element use $col[0]['short'].
If you only want to output one element anyways you can add LIMIT 1 to the MySQL query.
After querying you should check if the result array is set otherwise php will throw an error saying that $col[0]['short'] is not set.
There are three mysql_fetch functions which getting rows:
mysql_fetch_array() Fetch an array with both indexes (numeric and associative)
mysql_fetch_num() Fetch an array with numeric indexes
mysql_fetch_assoc() Fetch an array with associative indexes
In your example you will get an array that is looking like this one for the function mysql_fetch_array():
array(2) {
[0]=>
string(3) "foo"
["short"]=>
string(3) "foo"
}
$statement = 'SELECT short FROM textos';
$result = mysql_result($statement);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
var_dump($row); // or echo "<b>Short:</b>".$row['short']."<br/>"; or something else you like to do with rows of the above statement
}
}