This question already has an answer here:
I am new to phpMySQL and php. and I am trying to get a value from database and put it in a textbox. Currently, I only have 1 value in my table to test the code:
This is my code:
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "dbtest";
$tbl_name="tbltest";
$con = mysql_connect("$mysql_hostname","$mysql_user","$mysql_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("$mysql_database", $con);
$all = mysql_query("SELECT Balance FROM tbltest");
?>
And then in my HTML side, I have this:
<input type="text" name="Balance" value="<?php echo $all; ?>" />
But when I tried to run the code the value that appears in the textbox is:
Resource Id #4
What did I miss? Thank you for the help
</div>
mysql_query
does not return the result itself, but returns the resource that holds the result.
You can use mysql_fetch_assoc
or other relevant to fetch one row from that resource.
The code should be like: $con = mysql_connect($mysql_hostname, $mysql_user, $mysql_password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysql_database, $con);
$res = mysql_query("SELECT Balance FROM tbltest");
$all = mysql_fetch_assoc($res); //actually $all is not all the result, it's first row.
// $all might be like array('Balance' => '100');
and HTML part, as arrays could not be echoed directly('Array' is shown instead), you have to specify the index of $all:
<input type="text" name="Balance" value="<?php echo $all['Balance']; ?>" />
Mysql_query() returns a result resource.
When you echo the return, php is converting it into a string. You will need to use a mysql_fetch_array() function:
$all = mysql_query( "SELECT Balance FROM tbltest" );
foreach(mysql_fetch_array($all) as $row)
{
$balance = $row['Balance'];
}
echo '<input type="text" value="' . $balance . '">';
Also, these functions are depreciated. They are not supported any more. You should look into PDO or mysqli.