Unexpected result, I obtain always 0 in row[2]. Why? - php

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);
...
}

Related

last record of php (json) on an array then add 1

I did this question before but I have new data to make me understand.
I need to know how to get the last record of an array in php for a web service? I need to get it, add 1 and then create a new register (with the number+1 in another record
id turnoActual
106 7
get the last number, add 1 and then add another record with the number added (automatic, no adding new parameters with the AndroidStudio) and then get it at the result. So, I get the 7, add one, put into the SQL and then get the 8 as the result variable.
id turnoActual
106 7
107 8
Ty for the help, my regards, Santiago.
Code in php is like this and Im stuck and I dont know where to see.
ultimoTurno = LastTurn
nuevoTurno = newTurn
<?PHP
$hostname_localhost ="xxxxxxx";
$database_localhost ="xxxxx";
$username_localhost ="xxxxx";
$password_localhost ="xxxxx";
$json=array();
$conexion = mysqli_connect($hostname_localhost,$username_localhost,$password_localhost,$database_localhost);
$ultimoTurno="select MAX(turnoActual) from tn";
$resultado=mysqli_query($conexion,$ultimoTurno);
if($registro=mysqli_fetch_array($resultado)){
$nuevoTurno=$registro['turnoActual']+1;
$atendido=false;
$nuevoTurno_query="INSERT INTO tn(turnoAcutal, atendido) VALUES ('{$nuevoTurno}','{$atendido}')";
$resultado2=mysqli_query($conexion,$nuevoTurno_query);
if($resultado2){
$confirmacion="SELECT turnoActual FROM tn WHERE turnoActual = '{$nuevoTurno}'";
$resultado3=mysqli_query($conexion,$confirmacion);
if($registro=mysqli_fetch_array($resultado3)){
$json['usuario'][]=$registro;
}
else{
$result["turnoactual"]='no registra de resultado 3';
$json['usuario'][]=$resultar;
}
}
else{
$resulta["turnoAcutal"]='No Registra de resultado 2';
$json['usuario'][]=$resulta;
}
mysqli_close($conexion);
echo json_encode($json);
}else{
$resulta["turnoAcutal"]='No Registra de resultado';
$json['usuario'][]=$resulta;
echo json_encode($json);
}
?>
Explanation
I just tested this over and over in phpMyAdmin:
INSERT INTO tn (turnoActual) SELECT IFNULL(MAX(turnoActual) + 1, 1) FROM tn
This will work without error regardless of if there are any rows in the table. When there are no rows, the default value of 1 is applied.
It is advisable to lock your table before performing this query to avoid a race condition.
If you need to grab the data from your newly added row, use php's insert_id.
This answer assumes that you have been truthful about the number of columns (2) in your table and that the id column is PRIMARY and AUTOINCREMENT.
Hmm, your coding attempt references atendido but you won't be able to save false -- you can save null though. If you make that column nullable and don't reference it in the INSERT, it will default to NULL which should be sensible for your project.
I also want to point out that mysqli_fetch_array returns an array with indexed and associative elements. If you only want to store the associative keys in your output, then use mysqli_fetch_assoc().
Here's a little sample snippet to get you started (I tested this locally to be successful; no table locking implemented):
if (!$conexion = new mysqli("localhost", "root", "", "dbname")) { // declare and check for a falsey value
echo "Connection Failure"; // $conexion->connect_error <-- never show actual error details to public
} elseif (!$conexion->query("INSERT INTO tn (turnoActual) SELECT IFNULL(MAX(turnoActual) + 1, 1) FROM tn
")) { // execute and check for a falsey return value
echo "Insert Failure - Syntax Error"; // $conexion->error <-- never show query or actual error details to public
} elseif (!$result = $conexion->query("SELECT * FROM tn WHERE id = " . $conexion->insert_id)) {
echo "Select Failure - Syntax Error"; // $conexion->error <-- never show query or actual error details to public
} else {
echo "<pre>";
var_export($result->fetch_row());
echo "</pre>";
}
You can get the last item with end().
$arr = json_decode($json, true);
$last = end($arr);
$arr[] = $last+1;
Example: https://3v4l.org/eaLg2

PHP Count Arrays from MySQL counts Incorrectly

I am having trouble correctly counting elements within the array that I pulled from my database. Please see my code below:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
//NEW QUERY TO OUR DATABASE
$query = $conn -> query("Select distinct Race from Races");
while($race[] = $query->fetch_object());
//Check how many elements are within our query
$racecount = count($race);
echo "<br>" . $racecount . "<br><br>";
$racecount = count($race,COUNT_RECURSIVE);
echo "<br>" . $racecount . "<br><br>";
var_dump($race);
echo "<br><br><br>";
Using both type count() in both ways yields the same result of "4". However, please see the result from my var_dump.
array(4) { [0]=> object(stdClass)#3 (1) { ["Race"]=> string(5) "Human" } [1]=> object(stdClass)#4 (1) { ["Race"]=> string(7) "Vampire" } [2]=> object(stdClass)#5 (1) { ["Race"]=> string(5) "Demon" } [3]=> NULL }
Var_dump shows that it is an array with 4 elements within it. So count was correct, it's just not giving me the number that I'm looking for.
Thus, I have three questions.
1) How do I count my elements correctly?
2) Could someone explain to me why this reads as 4 elements?
3) Is my array not multi-dimensional? (since both counts yield the same result of 4)
Best Regards and Thanks in advance,
Josh
`while($race[] = $query->fetch_object());`
$query->fetch_object() returns a null to indicate that there are no more entries in the dataset, but you're still assigning that null value to your $race array as a last entry, and only then allowing the while to terminate its loop.... that's why you have 4 entries in the array rather than 3.
Your array is not multidimensional, because the entities stored in the $races array are objects, not arrays; it would only be multi-dimensional if it was an array of arrays
The reason is actually pretty straight forward. When inserting data into your array using while($race[] = $query->fetch_object()) you always insert the final $query->fetch_object() which is gonna be equal to null. That is when you exit your while loop. Thus, your array's last item will always be null, just like in your own var_dump.
One way to fix this would simply to subtract 1 from your result. Another way would be to implement inserting like this:
$race = [];
while($row = $query->fetch_object()) {
array_push($race , $row);
}
The best way to count however would be by simply executing an SQL COUNT command:
$query = $conn->query("SELECT COUNT(DISTINCT Race) FROM Races");
Your php count is returning the amount of fields on your result object, not the amount of rows.
Try this for your SQL query:
$query = $conn->query("SELECT COUNT(DISTINCT Race) FROM Races");
Should you wish to use the same query as you have now, try:
$raceCount = $query->num_rows;

mysql query looped with results stored in an array

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++;
}

MySQLi query stops at first item in a column when I need all items

I want to get all the image_name values from one of my tables where the category and account_id match.
The query joins 3 tables.
I am using mysqli.
SELECT image_name
FROM add_images, item, user_item
WHERE user_item.account_id = '$accountId' AND item.category = '$category';
However when this query executes and var_dump() the result, I find only the first record? there should be 8 items?
I have confirmed this by returning count() on the array which returned 1.
If I run this query in phpmyadmin the query runs successfully and it finds all 8 items, however they are repeated 8 times, not sure what that is about?
I have replaced image_name with * also I have tried image_name.* and image_name* all fail in my code and in phpmyadmin.
When I dump out the object I get:
object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(512) ["type"]=> int(0) } int(1) string(29)
I have also tried the following suggested in:
How get all values in a column using PHP?
while($row = mysqli_fetch_array($result,MYSQL_ASSOC))
but the suggested code also fails.
Below is my code:
public function searchItems($accountId, $catagory,$userId){
$imagePath = "D:\imagesdb\images\\" . $userId;
$thumb_path = $imagePath . "t\\";
$conn = $this->create_connection('read');
$sql = "SELECT image_name FROM add_images, item, user_item WHERE user_item.account_id='$accountId' AND item.catagory='$catagory'";
$result = $conn->query($sql)or die(mysql_error());
var_dump($result);
while ($row = mysqli_fetch_array($result)){
$path = $thumb_path . $row['image_name'];
$result = count($path);
var_dump($result);
return $path;
}
$conn->close();
}
I have also tried a prepared statement I have the same issue which I expected!
Does anyone have any suggestions please? This has been driving me mad!
You are returning $path unconditionally in the while-loop. So the function returns after it has fetched one row. This is probably not what you intended.
You probably want to create an array, add all image paths to that and return the array at the end of the function.

Comprehension disconnect in MySQL

Novice Alert
A mySQL table "tokens" contains a field, "dl" (DL), which is an integer (values: 0, 1 or 2)
For the row where field "token"==$stripped_token, the current value of "dl" is 0
I wish to read the record, increment the number found in field "DL" (zero) and update the record. Here's what I'm trying:
function sql_update_token($stripped_token)
{
global $mysqli ;
$curr_dl = $mysqli->query("SELECT dl FROM tokens WHERE token = ".$stripped_token) or die (mysqli_error());
$new_num = $curr_dl + 1;
$result = $mysqli->query("UPDATE tokens SET dl=".$new_num." WHERE token = ".$stripped_token) or die (mysqli_error());
}
The value of field DL is now "2" ! Why 2?
In troubleshooting the above, I tried this:
function sql_get_dl($stripped_token)
{
global $mysqli ;
$curr_dl_num = $mysqli->query("SELECT dl FROM tokens WHERE token = ".$stripped_token) or die (mysqli_error());
return $curr_dl_num;
}
$test = sql_get_token($stripped_token);
echo('[$test] == [ '.$test.' ]<br />');
The problem is that $test does not contain the number "0", as I had hoped. Instead, it contains: "current_field", "field_count", "lengths", "num_rows" and "type" (those text strings, in an array.
What are my errors?
One problem is that msysqli->query doesn't return the value you think it returns. It returns a result object. You then need to get at the data in that result. i.e.:
global $mysqli ;
$result = $mysqli->query("SELECT dl FROM tokens WHERE token = ".$stripped_token) or die (mysqli_error());
$row = $result->fetch_row();
$curr_dl_num = $row[0];
Think of $result as a table. fetch_row() gets the first row, and $row[0] gets the first cell of that row. This is really inconvenient, since you are only getting a table with one value in it, but with other queries, where multiple results are returned, being able to step through them using fetch_row() is really useful.
As well, how are you generating your $stripped_token value, since you said that wasn't behaving as you expected? If you are reading it from a mySQL query, your problem is probably the same - it might be a result object, and not a single value as you expect.
EDIT:
Never mind the bit about $stripped_token, I misinterpreted the last part of your question.

Categories