I am trying to output values saved in my database into a div field, however the data does not seem to come out, could anyone explain to me why?
<div>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="Database"; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result=mysql_query("SELECT from `posts`");
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
echo $result[$i];
$i++;
}
?>
</div>
Above is the code I have inside the div tag. So my question why does my echo not work?
This is not the way to do that, you may use like this:
//$result=mysql_query("SELECT from `posts`"); <- this query is wrong.
if ($result = mysql_query("SELECT * FROM posts"))
{
$num=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
echo $row['key']; // <- you must set the field name of your query here
}
}
else // This if will show you when any query error is thrown.
{
echo mysql_error();
}
Your original query is wrong. You may get an error because SELECT FROM is not valid. You have to specify a list of fields, a function or * to get all fields of the table.
The you may use mysql_fetch_assoc(), mysql_fetch_row() or mysql_fetch_array() in order to fetch the received data from the query.
Plus, I have added an if in your query command in order to get any mysql error thrown in your query execution. Using that you'll never be confuse about what happened here.
Hope it helps.
UPDATE: As #SpiderLinked said(Thank you dude), mysql_numrows() does not exists. You have to use mysql_num_rows() to get query result count.
"SELECT from `posts`"
is not a valid query.
This would be:
"SELECT * FROM `posts`"
Also the following won't pull any results from your database:
while ($i < $num) {
echo $result[$i];
$i++;
}
You would need to loop around the results as you fetch them:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
try this....
<div>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="Database"; // Database name
$result=mysql_query("SELECT * FROM posts");
$num=mysql_numrows($result);
if($num>0) {
echo $num." rows returned";
while ($row = mysql_fetch_assoc($result)) {
echo $row['key'];
}
} else {
echo "No Rows Returned";
}
?>
</div>
There are several errors with your code...first....you do not give the result of the query to any variable...second...your query is wrong...third... there is no such function as mysql_numrows()....here is an example of what it should look like:
<div>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="Database"; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result=mysql_query("SELECT * FROM posts") or die (mysql_error()); //added die for debugging purposes
while ($num=mysql_fetch_array($result)) {
echo $num['COLUMN NAME HERE!'];
}
?>
Also...please stop using mysql_ while it is deprecated...
Related
I have following PHP page which queries MYSQL TABLE and displays the result.
<?php
$host="localhost";
$username="root";
$password="PASSWORD"; // Mysql password
$db_name="syslog"; // Database name
$tbl_name="logs"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//$sql="SELECT * FROM $tbl_name ORDER BY `LOGS` datetime LIMIT 0 , 10";
$sql = "SELECT * FROM `logs`\n"
. "ORDER BY `logs`.`datetime` DESC LIMIT 0, 50 ";
$result=mysql_query($sql);
// Define $host_column=1
echo '<table width="1400" border="1" align="left" cellpadding="1" cellspacing="1">';
echo '<tr><th>ID</th><th>Host</th><th>Date</th><th>Info</th><th>Type</th><th>Messgae</th></tr>';
while($rows=mysql_fetch_array($result)){
//$host_column assign here from result
$host_column=$rows['host'];
// show alternate colors based on colum result
$priority_column=$rows['priority'];
if($priority_column=='err'){
echo "<tr bgcolor='#FFA07A'><td>".$rows['seq']."</td><td>".$rows['host']."</td><td>".$rows['datetime']."</td><td>".$rows['priority']."</td><td>".$rows['program']."</td><td>".$rows['msg']."</td></tr>";
}else if($host_column=='10.0.0.1'){
echo "<tr bgcolor='#bbbbbb'><td>".$rows['seq']."</td><td>".$rows['host']."</td><td>".$rows['datetime']."</td><td>".$rows['priority']."</td><td>".$rows['program']."</td><td>".$rows['msg']."</td></tr>";
}else if($host_column=='10.0.0.2'){
echo "<tr bgcolor='#cccccc'><td>".$rows['seq']."</td><td>".$rows['host']."</td><td>".$rows['datetime']."</td><td>".$rows['priority']."</td><td>".$rows['program']."</td><td>".$rows['msg']."</td></tr>";
}
}
echo '</table>';
mysql_close();
?>
The results are in thousands, therefore I wanted to have per page result with next page option including how many pages are there , next previous. Also I would like to have an action button on each row , like DELETE , EDIT and when I click on it, it should perform an action of my choice like goto another php with action delete/edit this entry number. I done pagination with simple page, but integrating part is where I am failing plus adding action buttons (or text)
Consider doing the pagination on the SQL side, by passing pageIndex and pageRecordCount.
... LIMIT {pageIndex * pageRecordCount}, {pageRecordCount}
I am trying to display a record from a mysql database depending on the char posted from a form input. But I can't get this to work.
My HTLM code is below
<form action='headcode_Db_connect.php' method='POST'>
<input type="text" name="headcode" value="" maxlength="2">
</form>
My PHP code
<?php
$headcode = $_POST['headcode'];
echo $headcode;
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="789852"; // Mysql password
$db_name="work"; // Database name
$tbl_name = "headcodes";
// Connect to server and select database.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Retrieve all data from the table
$sql = "SELECT * FROM $tbl_name WHERE LIKE '%$headcode%'";
$result1 = mysql_query($sql, $link);
// if successfully, displays message "Successful".
if($result1){
$connect = "connected";
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
while ($row = mysql_fetch_assoc($result1)){
$number = $row['number'];
}
echo $number;
?>
I keep getting an error. The data being sent will be 1A or 2A and should display the number from the database for this record. If I change WHERE LIKE '%$headcode%'"; to WHERE headcode = '1A'"; I get a result of 17 which is correct. So how can I use the POST variable to give this result.
WHERE LIKE '%$headcode%'"
If you searched for at (for example), the following would all match:
at, bat, cat, rat
However , if you lose the first %, It must start with your search term letters
WHERE LIKE '$headcode%'"
which would return all words beginning with at. Hope this helps!
I got it working with the below code.
<?php
$headcode = $_POST['headcode'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="789852"; // Mysql password
$db_name="work"; // Database name
$tbl_name = "headcodes";
// Connect to server and select database.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Retrieve all data from the table
$sql = "SELECT * FROM $tbl_name WHERE headcode = '$headcode'";
$result1 = mysql_query($sql, $link);
if($result1){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
while ($row = mysql_fetch_assoc($result1)){
$number = $row['number'];
}
echo $number;
?>
I am working on simple game.
When user view scores of all users I want his score to be in different color. How can I do it?
So far I have just list of all scores from highest score to lowest
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name ORDER BY score DESC;";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
?>
<HTML TABLE>
<?php
}
mysql_close();
?>
Test whether the player in the row is the current player, and set a class. Then use CSS to assign a color to that class.
while ($row = mysql_fetch_assoc($result)) {
$class = $row['player'] == $current_player ? 'class="highlight"' : '';
echo "<tr $class>";
// code for rest of table row
echo "</tr>";
}
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 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.