I have a php file with two mysql queries and an if statement for each query. I'd like the final output to combine the two results and separate with a comma. Right now, the first if statement is working, but the second is not.
$result = mysql_query("SELECT round(AVG(cop),1) AS 'avg_cop' FROM table WHERE timestamp >= subdate((select max(timestamp) from table), interval 1 week)");
if ($result < 3.41)
{
$ret = "example text 1";
} else {
$ret = "na";
}
$result1 = mysql_query("SELECT round(AVG(temp),1) AS 'avg_temp' FROM table WHERE timestamp >= subdate((select max(timestamp) from table), interval 1 week)");
if ($result1 < 53)
{
$ret1 = "example text 2";
} else {
$ret1 = "na";
}
echo $ret.", ".$ret1;
In this instance, I know that the first query results in a "1.1" value and the second results in a "69.4" value. But, the final result I get is "example text 1, example text 2" when it should be "example text 1, na". Any ideas on what I'm doing wrong?
mysql_query doesn't return the row itself, it returns a resource that you need to pass into a function like mysql_fetch_array() or mysql_fetch_assoc() to deal with the table result; you can't just simply use the return value from mysql_query.
It would also probably be better if you just combined the SQL queries into one.
$result = mysql_query("SELECT round(AVG(cop),1) AS 'avg_cop', round(AVG(temp),1) AS 'avg_temp' FROM table WHERE timestamp >= subdate((select max(timestamp) from table), interval 1 week)");
$row = mysql_fetch_assoc($result);
if ($row['avg_cop'] < 3.41)
{
$ret = "example text 1";
} else {
$ret = "na";
}
if ($row['avg_temp'] < 53)
{
$ret1 = "example text 2";
} else {
$ret1 = "na";
}
echo $ret.", ".$ret1;
$result and $result1 are currently strings. You want to add:
$result = mysql_query("SELECT ... // unchanged");
$result = floatval($result)
if ($result < 3.41)
and for $result1
$result1 = mysql_query("SELECT ... // unchanged");
$result1 = floatval($result1)
if ($result1 < 53.0) // note the addition of the .0 to compare one float to another
Do not use MYSQL it has deprecated since PHP 5, use MYSQLi or PDO instead; they are much safer a provide you with improved features.
It is also good pratice to assign a null value to a PHP variable before assigning it a value, especially in this case ($ret ="" then you may change the value).
Finally, the results from mysql_query() is a resource, you need to iterate through it to get the proper values:
while ($row = mysql_fetch_assoc($result)):
//Do something with $row['avg_temp'];
endwhile;
Hope this helps!
Related
I am using PHP and MySQL (mysqli) in XAMPP, I have a drop down, and the user must choose one, then a query is used to find the id of the value that has been chosen but it does not work. I have already done this three more times and it worked but this one doesn't.
$sql = "SELECT foo_id FROM foo_table
WHERE foo_name = 'bar';";
$res = $conn->query($sql);
for ($i = 0; $i < 500; $i++) {
$row = $res->fetch_assoc();
echo $row[row["foo_id"]]
}
The problem is that fetch_assoc does not return anything even though the $res variable returns true.
Edit: I forgot to mention that running the query in phpmyadmin returns results normally.
I am not sure why you are iterating over 500 times? this doesn't make sense.
Best practice to retrieve the data from DB is
$sql = "SELECT foo_id FROM foo_table
WHERE foo_name = 'bar'";
$res = $conn->query($sql);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo $row["foo_id"];
}
}
OR
$foo_id = ''
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
$foo_id = $row["foo_id"];
}
}
for ($i = 0; $i < 500; $i++) {
echo $foo_id;
}
I found the solution, the problem is that the real database used greek characters in the records and the database had to be set to utf8-bin, after doing so, it worked.
So I have fetched data from a MySQL database and I want to assign it to a variable based on an nth row. Only the bottom three rows are filtered and I want to assign values from the firs and last row to two variables.
$sql3 = "SELECT * FROM login_attempts WHERE login_attempt_user_id=? AND login_attempt_result=? ORDER BY login_attempt_id DESC LIMIT 3;";
$stmt3 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt3, $sql3)) {
echo 6;
exit();
} else {
mysqli_stmt_bind_param($stmt3, "ss", $login_attempt_user_id, $login_attempt_success);
mysqli_stmt_execute($stmt3);
$result2 = mysqli_stmt_get_result($stmt3);
if (mysqli_num_rows($result2) > 0) {
while ($row2 = mysqli_fetch_assoc($result2)) {
$test1 = $row2['login_attempt_time'][0];
$test2 = $row2['login_attempt_time'][2];
echo $test1.$test2;
exit();
}
} else {
//echo 4;
exit();
}
}
The section of code is within the while loop and I realize that what I am attempting is for arrays. I want to do something similar to achieve my goal.
My code is not assigning the database entry to the variable: $test = $row2['login_attempt_time'] assigns the last value of the fetched row, however $test = $row2['login_attempt_time'][0] only returns the value 1.
Would anyone please be able to help with this?
Fetch all (three) rows into an array (2-dimensional) with mysqli::fetch_all(). Then get the first and the last elements (rows) with reset() and end().
Change
while ($row2 = mysqli_fetch_assoc($result2)) {
$test1 = $row2['login_attempt_time'][0];
$test2 = $row2['login_attempt_time'][2];
echo $test1.$test2;
exit();
}
to
$data = $result2->fetch_all(MYSQLI_ASSOC);
$variable1 = reset($data); // first row
$variable2 = end($data); // last row
Remember, this mysqli_fetch_assoc($result2)) will fetch one row from the database. So the first time, $row2 will be the contents of the first row, the second time $row2 is the second row, etc. Perhaps add a counter to the loop to know when to populate $test1 and $test2, as with an if condition.
I'm fairly new to PHP and I've been stumped on this issue for a while now (been searching everywhere but no help really).
I'm attempting to search for all the data in a data table ("Select * FROM X") and that seems to work fine.
However when I try to return/echo the data, encoding into JSON format as an array (I'd like 1 row as 1 index in the array) it does wierd things.
Heres the code I currently use;
$SQL = "SELECT * FROM `units`";
$Result = mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total > 0)
{
$rows = mysqli_fetch_array($Result, MYSQLI_NUM);
$row_count = mysqli_num_rows($Result);
while($row = mysqli_fetch_array($Result))
{
echo json_encode(array($row));
}
}
This then gets used in Unity (C#) via;
JSONObject obj = new JSONObject(loadUnitsWWW.text);
Debug.Log(obj);
The results of which are;
[{"0":"2", "unitID":"2","1":"Tanks","unitName":"Tanks","2":"Ground","unitType":"Ground"},[],[],[],[],[],[],[],[],[],[],[]]
it seems to be trying to return EVERYTHING for some reason, including the column names. But I've no idea why it'd return the same results multiple times (and no idea where the 0 came from).
As I said, I'm fairly inexperienced with PHP, as such its very likely something (in fact I'm certain) something is wrong with that code, I've tried a for loop such as;
for($i = 0; $i < $row_count; $i++) {...}
but to no avail (it returns something like:
["1",[],[],"",null,null,null,{},null,null,null.null[],""..........]
Heres the data table layout if it helps;
unitID | unitName | unitType
1 | infantry | Ground <br>
2 | Tanks | Ground <br>
3 | Support | Ground <br>
4 | Artillery | Ground <br>
. <br>
.
There are 13 items in the table
EDIT:
THis is what I am expecting:
[["1", "Infantry","Ground"],["2","Tank","Ground"]....]
Here is how you should be doing this. comment in code
// Always use the field names. this is going to avoid debug nightmare later.
$SQL = "SELECT unitID, unitName, unitType FROM `units`";
$Result = mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total > 0)
{
// initilize a new array
$data = array();
// Note use mysqli_fetch_row because you want only result values
while($row = mysqli_fetch_row($Result))
{
// add the row data to our array
$data[] = $row;
}
// encode the entire data and echo
echo json_encode($data);
}
Reference : mysqli_fetch_row
Edit: you can also do this like the following.
if($Total > 0)
{
// Get all the result at once and json_encode it!!
echo json_encode(mysqli_fetch_all($Result));
}
Reference: mysqli_fetch_all
Edit2: as per #YourCommonSense comment your code can be
$SQL = "SELECT unitID, unitName, unitType FROM `units`";
if ($Result = mysqli_query($link, $SQL))
{
echo json_encode(mysqli_fetch_all($Result));
} else die ("DB ERROR");
There are 2 issues with your php snippet:
if you look at the mysqli_fetch_array documentation, you'll notice that if you don't supply the second int $resulttype argument, it defaults to MYSQLI_BOTH; this means that both associative and numeric indices will be returned
you call mysqli_fetch_array on $Result twice, first assigning it to $rows variable, and second time inside the while condition assigning it to the $row variable
I'm guessing what you want to do is:
remove the $rows assignment
inside the while condition add the 2nd argument MYSQLI_NUM
0 refers to column order in the result set. You can refer to mysqli-result.fetch_array and check parameters and return type.
change your line:
while($row = mysqli_fetch_array($Result))
with:
while($row = $rows) {
// your code
$rows = mysqli_fetch_array($Result, MYSQLI_NUM);
}
Another solution, I think it is better for you
$rows = mysqli_fetch_all($Result, MYSQLI_NUM);
echo json_encode($rows);
I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}
I have a table set up in MySQL with two columns:
ID (auto_increment)
recentlyplayed (VARCHAR, set up like "1 44" or "2 140", etc)
I'm trying to get the mysql data into an array and compare it to something defined outside MySQL. But it doesn't seem to work for some reason. Here is my code:
$whichPlaylist is a 1 character INT, and $num is a 3 character INT.
//Note: These values are actually received through file_get_contents('textfile.txt');
$whichPlaylist = "1";
$num = "44";
//Combine playlist number and video number
$joint = $whichPlaylist. "" .$num;
//Insert joint var into Mysql database
mysql_query("INSERT INTO recentlyplayed (numplayed) VALUES('$joint') ");
$query = "SELECT * FROM recentlyplayed";
$result = mysql_query($query) or die ("no query");
while($row = mysql_fetch_array($result))
{
$stored[] = $row['1'];
}
if (in_array($joint, $stored['1'])){
$reroll = 1;
}
echo $reroll;
Even if the same value of $joint is in the MySQL table, $reroll doesn't echo 1. Could this because of extra spacing when inserting the $joint variable? I'm actually getting the $whichPlaylist and $num from a text file that has a new line after the number. Any help is appreciated. :)
Move the While End braces after if statement, and see if it works.
Try this code in your script:
$stored = array();
while($row = mysql_fetch_array($result)) {
$stored[] = $row[1];
}
if (in_array($joint, $stored)){
$reroll = 1;
}
The array is $stored (not $stored['1']).