I have this code in PHP
$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
then the output be:
The max num is this is it
hh
Why didn't the query get the max number?
The table is called info and it has these fields, ID, num, title, description, and answer.
After editing:
I tried my query in MySQL and it works fine!
"SELECT MAX(num) FROM info"
and this is my complete code if it can help:
<?php
$answer=$_GET["answerbox"];
$ID=$_GET["TheID"];
$host="localhost";
$username="root";
$password="";
$db_name="game";
mysql_connect("$host","$username","$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)) {
echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
$sql="SELECT * FROM info WHERE ID=".$ID;
$query = mysql_query($sql) or die(errorquery);
$row = mysql_fetch_array($query);
$trueanswer = $row['Answer'];
$num=$row['num'];
if ($num<$maxnum)
{
$numto= $num +1 ;
echo "<br>".$maxnum."hh";
}
?>
Then the code will be
$max="SELECT MAX(num) as num FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_assoc($maxquery)) {
echo "The max num is ". $row['num']."this is it";
}
The column you are looking for in the result set is NOT called num. Try print_r($row); to see what the array indices are, or give it an alias, e.g.
$max="SELECT MAX(num) AS max_num FROM info";
...
echo "The max num is ". $row['max_num']
Here is another and simpler way:
$query="SELECT MAX(num) FROM info";
list ($max) = mysql_fetch_row(mysql_query($query));
print ($max);
num field in your database has to be a numeric datatype (i.e. int, float etc) in order for this to work properly.
It's because your query returns a scalar value, not an array. $maxquery is the value you want to get.
I recommend checking your query against the database before try running it with PHP.
Run your query within the MySQL query window then analyse the output. That way you can concentrate on the query without the PHP getting in the way.
Once you've done that modify the question so that we can see the query that's actually being run.
The query is looking fine. Please inspect your code of getting data from the result set step by step.
Related
I built a website that takes a random row from a MySQL table.
The values I am interested in are Exercise and solution.
When I check if the solution the user wrote is the same as the one I got from the database, a new query is running and replacing my solution.
the query:
$query="SELECT Exercise,solution FROM exercises WHERE rank = '".$Rank."' ORDER BY RAND() LIMIT 1";
$result=mysql_query($query) or die ("Query to get data from firsttable failed: ".mysql_error());
while ($row=mysql_fetch_array($result)) {
$Exercise=$row["Exercise"];
$Solution=$row["solution"];
checking the answer:
<?php
if (isset($_POST['postBTN']))
{
if($_POST['solution'] == $Solution){
echo "<script type='text/javascript'>alert('yes');</script>";
$progression = ($progression+1);
$query="UPDATE users SET progression = '".$progression."' WHERE username = '".$_SESSION['username']."'";
$result=mysql_query($query) or die ("Query to get data from firsttable failed: ".mysql_error());
}else{
echo "<script type='text/javascript'>alert('no');</script>";
}
}
?>
When I check the answer a new query is running and replacing the solution.
My table in the database contains 3 columns that all has qwe for a username and have the respective dates of January, February and March but when I try to echo them it only displays January. I'm trying to get them all into a drop down list but I can't get past this so I have to make sure I get all of these dates before I put them elsewhere.
{
$con=mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request="SELECT date FROM mytable WHERE username='qwe'";
$result=mysqli_query($con, $request);
$fetch=mysqli_fetch_assoc($result);
echo $fetch['date']; echo "<br>";
print_r($fetch);
}
You are missing loop, data come up. You can see when you are printing data using print_r($fetch), use loop to show one by one.
And also try to don't use user input directly in query before checking mysql injection. like you have putted username='qwe' if username is user input then use it like this directly in query Suggestion for query
$request = "SELECT date FROM mytable WHERE username=".mysql_real_escape_string('qwe');
and your with loop try this,
$con = mysqli_connect('localhost', 'root', '') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request = "SELECT date FROM mytable WHERE username='qwe'";
$result = mysqli_query($con, $request);
print_r($fetch);
while ($fetch = mysqli_fetch_assoc($result)) {
echo $fetch['date'];
echo "<br>";
}
?>
I want to get variable data "$b ,$d, $f,$h" from database and then calculate it. Here is my example:
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="cbrteh"
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$b= mysql_query("SELECT bobot FROM atribut where id= 1");
($row = mysql_fetch_assoc($b));
$row["bobot"];
$d= mysql_query("SELECT bobot FROM atribut where id= 2");
($row = mysql_fetch_assoc($d));
$row["bobot"];
$f= mysql_query("SELECT bobot FROM atribut where id= 3");
($row = mysql_fetch_assoc($f));
$row["bobot"];
$h= mysql_query("SELECT bobot FROM atribut where id= 4");
($row4 = mysql_fetch_assoc($h));
$row["bobot"];
$calc = $b+$d+$f+$h;
echo $calc;
<?
The values in the database are 50,50,50,50 but the result is 22. Why is this?
The line below every query string is wrong
($row = mysql_fetch_assoc($b));
$row["bobot"];
Because you are not storing the result anywhere.The correct way to get the values should be:
if(count($res=mysql_fetch_assoc($b))>0)$_b=$res[0]['bobot'];
(if returning result has at least one row, return the value to $_b variable)
Mind that $b is being used to store the query result, not the value you get from it.
Then you sum the results like this:
$calc = $_b+$_d+$_f+$_h; and that's all.
It seems you could do all the work in your database:
$query = mysql_query(
"SELECT SUM(bobot) AS summation FROM atribut where id IN (1,2,3,4)"
);
$row = mysql_fetch_assoc($query);
$calc = $row['summation'];
I've removed the unnecessary brackets around the assignment to $row, and of course I've replaced four separate lookups with just one. Since I've used the grouping function SUM, I have aliased it as summation so it is easy to retrieve from the row.
I want to show the maximum value of a particular column of mysql table in php. Here is my code:
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$var = $_POST['value'];
$sql = mysql_query(" SELECT MAX(column) FROM tableName WHERE variable='$var' ") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
echo "Maximum value is :: ".$row['column'];
?>
output:::
Maximum value is ::
Or you could be a bit creative:
$sql = mysql_query("SELECT `column` FROM tableName WHERE variable='$var' ORDER BY `column` DESC LIMIT 1") or die(mysql_error());
This is the same problem that I was searching for a solution. The approach below worked. The solution was using "MYSQLI_NUM". While the code below gives the intended result it still seems way too complex. Is there a way to "short-cut" using the "while" statement to search an array since there is only one returned value?
Selecting a max value only returns one number, yet PHP still seems to require a loop to evaluate an entire array. I was expecting something easy, like: max_value=result(0).
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the database server');
$query = "SELECT MAX(IssueIDNUM) FROM tblIssueList";
$result =$conn->query($query);
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
$maxresult=$row[0];
echo $maxresult;
}
$result->close();
$conn->close();
?>
With further experimentation, I was also able to adapt the code by Jim H. to develop the following solution. Though it works the code still seems too complex.
// Solution #2
$result =$conn->query("SELECT MAX(IssueIDNUM) `max` FROM tblIssueList");
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $row['max'];
}
The real name of column is MAX(column), try:
print_r($row);
You may either do:
$sql = mysql_query(" SELECT MAX(column) AS `column` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Or:
$row = mysql_fetch_row($sql) or die(mysql_error());
echo "Maximum value is :: ".$row[0];
You have two choices. By Index or by Column Name. If you really want to use a column name, alias the column in your query.
$sql = mysql_query(" SELECT MAX(column) `max` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Then you can use
$row['max'];
or
$row[0];
You are probably not returning any rows. You should try WHERE variable LIKE '%$var%';
$sql = mysql_query(" SELECT MAX(column) AS GIVE_A_NAME FROM tableName WHERE variable='$var' ") or die(mysql_error());
and
echo "Maximum value is :: ".$row['GIVE_A_NAME'];
I want to display some basic data from a MySQL database. Here's the current code I have, but it doesn't seem to work. Could someone please explain why this doesn't work and offer a solution? Thanks!
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM 'users' ORDER BY 'DATE' DESC LIMIT 8';
echo = "'$result'"
?>
Providing your connection and structure information is correct, the following should work for you:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$query = mysql_query($result) or die("Query Error");
while($row = mysql_fetch_assoc($query))
{
echo = "'" . $row['user'] . "'";
}
?>
You forgot to query the database!
You need to use mysql_query() to retrieve data from your DB server, then loop through it with a while() loop.
Also, you can't use quotes inside quoted strings - it breaks the string, meaning you'll get a syntax error with the SELECT ... line. You don't actually need to quote database fields in queries, so the following should work fine:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM users ORDER BY DATE DESC LIMIT 8';
$result = mysql_query($query); // Query the database.
// Loop through each returned row
while($row = mysql_fetch_assoc($result))
{
print_r($row); // Prints the current row
}
?>
To show any errors that PHP reports, put these two lines at the top of your script.
error_reporting(E_ALL);
ini_set('display_errors', '1');
They will output any errors you get, making problems much easier to solve.
After the selecting the database need
$stmt = mysql_query("SELECT * FROM users ORDER BY DATE DESC LIMIT 8");
while ($result = mysql_fetch_array($stmt, MYSQL_NUM))
{
var_dump($result);
}
mysql_free_result($stmt);
You should query your string and then echo the result, like this for example:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$result = mysql_query($query);
echo = "'$result'"; // This may need a foreach loop
?>
You should escape the ' in your string, because you use them to open and close your string too. The syntax highlighter actually tells you that you are wrong ('users' and 'DATE' are black instead of maroon). :)
Please see the PHP.net documentation about strings:
After that, you'll need to further process $result. It is just a resource pointer and cannot be echoed that way. But that's a second step. :)