Reputation: 158
I've written a script that in short is supposed to query data from the database and echo a result into a HTML form field. However, I have been unsuccessful. Please see code below:
<?php
include("dbconfig.php");
$val = '6';
$result = mysqli_query("Select * from test where testid= '$val'");
$name = (mysqli_num_rows($result)==1) ? mysqli_fetch_assoc($result) : null;
if(is_array($name)){
?>
<html>
<body>
<form>
Name: <input type="text" id="firstname" value="<?php echo $name['firstname']; ?>"/>
</form>
<?php
} else {
echo "No such name exists";
}
?>
</body>
</html>
Can someone please tell me what I'm doing wrong. Because it won't echo anything into the field and I find it rather annoying because majority of the scripts I've come across are quite similar to this one.
Help will be much appreciated.
Thank You,
Sohail.
Upvotes: 1
Views: 3922
Reputation: 33813
I have tested the below and it works OK. @Fred-ii- gave you loads of good info, especially using error debugging - but you do need to supply the connection object which you were missing.
<?php
error_reporting( E_ALL );
include("conn.php");
$val = 6;
/* What is the name of the $connection object ? */
$result = mysqli_query( $conn, "Select * from `test` where `testid`='$val'" );
$name=( $result ) ? mysqli_fetch_assoc( $result ) : false;
?>
<html>
<head>
<title>Ya gotta have a title...</title>
</head>
<body>
<?php
if( !empty( $name ) ){
echo "
<form>
Name: <input type='text' id='firstname' value='{$name['firstname']}'/>
</form>";
} else {
echo "No such name exists";
}
?>
</
Upvotes: 1
Reputation: 74217
You did not pass your db connection to your query, so it never gets executed.
mysqli_
This line of code:
$result = mysqli_query("Select * from test where testid= '$val'");
needs to have a connection parameter:
$result = mysqli_query($connection, "Select * from test where testid= '$val'");
and is unknown to us as to which MySQL API you're using to connect with.
Your query may have failed, so check for errors.
$result = mysqli_query("Select * from test where testid= '$val'")
or die(mysqli_error($connection));
and replacing the $connection
variable with the one that you have assigned in your dbconfig.php
which is unknown to us.
Different MySQL APIs/functions do not intermix.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php and apply that to your code.
You're also open to an SQL injection. Use a prepared statement.
References:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
If you want to check if a row exists, see my other answer on Stack:
Upvotes: 0