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.
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";
}
?>
</
You did not pass your db connection to your query, so it never gets executed.
Assuming a successful connection using 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.
https://en.wikipedia.org/wiki/Prepared_statement
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/function.mysqli-connect.php
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:
https://stackoverflow.com/a/22253579/1415724
Related
I've tried the solutions in this question, however mysql has been depricated for mysqli. Even with these changes it still doesn't return the information, instead returns an error, with nothing else (Nothing is heard from mysqli)
What i'm trying to do is kind of similar to the question linked, however it would look like this in the url: example.com?view-work=A01 It would search for A01 in the database, then return the Name, description, an image URL and date it was made live.
This is the code that i've been able to make using the answers from the question:
<?php
//Establishing a connection to the Artwork Database
mysqli_connect('localhost', 'dbuser', 'dbpassword');
mysqli_select_db('db');
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_real_escape_string($artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($sql);
if (!$result) {
echo "Something's gone wrong! ".mysqli_error();
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>
Seems like the cause of these errors was my own incompetence, also probably the fact I'm kind of new to PHP and MySQL in general. I learnt that I needed to reference my connection in some of the commands for them to successfuly process after adding the debug exception mentioned in the OP's comments.
As someone also pointed out, Yes this code is still vulnerable to other types of SQL injection, I'll be addressing these before the final version of the code goes live.
Fixed Code:
<?php
//Establishing a connection to the Artwork Database
$link = mysqli_connect('localhost', 'dbusr', 'dbpasswd', 'db');
//Exeptional Debugging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (!$link) {
echo "Error: Unable to connect to MySQL!";
echo "Error No.".mysqli_connect_errno();
echo "Error in question: ".mysqli_connect_error();
exit;
}
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_escape_string($link, $artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($link, $sql);
if (!$result) {
echo "Something's gone wrong!"; //This line will be changed later to sound more professional
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>
<?php
error_reporting(0);
$link = mysqli_connect("localhost", "root", "", "checksql");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$myemailaddress=$_POST['useremail'];
$mypassword=$_POST['userpassword'];
$sql = mysqli_query("SELECT * FROM register WHERE Email = '$myemailaddress' ");
$count = mysqli_num_rows($sql);
echo $count;
if($count > 0){
echo "success";
} else{
echo "failed";
}
?>
I am trying to check whether an email exists in the database or not. I searched different thread on stackoverflow and tried to correct it but failed. Even the echo of $count isn't showing it's value. Is there any other way to check it?
You didn't pass db connection to your query
$sql = mysqli_query($link, "SELECT ...
^^^^^^
Btw, your code is open to SQL injection.
Use a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
More on SQL injection:
https://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/en/security.database.sql-injection.php
How can I prevent SQL injection in PHP?
Also make sure your POST arrays are not failing you.
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.
error_reporting(0); doesn't help you, it turns it off.
Add or die(mysqli_error($link)) to mysqli_query() to check for errors.
http://php.net/manual/en/mysqli.error.php
Your form should be using a POST method with name attributes for both your POSTs. That is unclear and wasn't posted in your question; call it an insight.
If you are using both your form and PHP/MySQL inside the same file, then that will trigger undefined index notices on initial page load.
Use !empty() for them.
Reference(s):
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/function.empty.php
I'm trying to create a searchable database using PHP and MySQL. I have a file called mission.html with the following code:
<html>
<body>
<form name="form1" method="post" action="mission1results.php" id="search">
<input name="search" type="text"/>
<input type="submit" name="submit" vaule="Search"/>
</form>
mission1results.php
<html>
<body>
<?php
include 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
if(mysqli_connect_error()){
die("Database Connection Failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
$q_cond = mysqli_real_escape_string($_GET['search']);
$query="SELECT * From Merchant Where MerchantName='".$q_cond."'";
$result=mysqli_query($connection,$query);
if ($result===false)
{
die("Database Query Failed!")
};
while ($row=mysqli_fetch_assoc($result)){
echo "MerchantName: ".$row["MerchantName"].",";
echo "<hr/>";
}
mysqli_free_result($result);
?>
<?php
mysqli_close($connection);
?>
</body>
</html>
When I hit submit and type in anything in the searchbar nothing appears. I don't get an error, I don't get results, its all blank. Can anyone tell me why this is?
You have a syntax error in mission1results.php
if ($result===false)
{
die("Database Query Failed!")
};
must be changed for:
if ($result===false)
{
die("Database Query Failed!");
}
Instead $_GET['search'] use $_POST['search'] because your submit forms method is post.
One of mysqli_real_escape_string parameters should be DB connection.
syntax errors in HTML, for example, vaule="Search"
syntax errors in PHP, for example, there shoudn't be ; after } in if
If you are getting a blank screen with the errors pointed out in previous answers you might want to take a look at the PHP error_reporting level on your system http://php.net/manual/en/function.error-reporting.php. You should be seeing PHP errors, on a development server I like to report PHP errors, warnings and notices.
Also, are you expecting users to enter an exact search term? You might want to consider something like:
$query="SELECT * From `Merchant` Where `MerchantName` like '%".$q_cond."%'";
First and foremost: mysqli_real_escape_string() requires a DB connection be passed, then there is your form where you are using a POST method in the form and GET for your query.
Consult the manual: http://php.net/manual/en/mysqli.real-escape-string.php
$q_cond = mysqli_real_escape_string($connection,$_POST['search']);
Plus, change
if ($result===false)
{
die("Database Query Failed!")
};
to
if ($result===false)
{
die("Database Query Failed!");
}
You also have a syntax error vaule="Search" change it to value
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: Error reporting should only be done in staging, and never production.
Also or die(mysqli_error($connection)) to mysqli_query() to find any possible errors.
i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?
I cant output the values of the row value to the html content any suggestions on how to do that? i tried using different methods so that i will print on the page but it's always blank is there any way to do it?
<?php
//connect
$dbh=mysql_connect ("localhost", "xxxx_admin", "xxxx")
or die ('I cannot connect to the database.');
mysql_select_db ("xxxx_Client");
$term = $_POST['term'];
echo $term;
$sql = mysql_query("select * from ClientTable where FName like '$term'");
if ($row['FName'] == $term){
$ID = $row['ID'];
$FName = $row['FName'];
$LName = $row['LName'];
$PHON = $row['PHON'];
}
else
echo "invalid input";
?>
<html>
<head>
<title></title>
</head>
<body>
asdadasdad<br>
<?php echo $FName; ?><br>a<br>
<?php echo $_POST["$LName"]; ?><br>a<br>
$FName <br>
$LName <br>
$ID <br>
$PHON <br>
sadasdasda
</bod>
</html>
First, you are probably not getting any results from your query. Typically when using LIKE you use some form of wildcard in the query like this:
select * from ClientTable where FName like '%$term%'
Second, you are not actually working with the result set.
You need to use some sort of mysql_fetch_array or similar to get the values into $row.
And of course, you really should not be using the mysql_* functions anyway as they are being deprecated in favor of mysqli_* or PDO.
Finally, your need to learn how to prevent SQL injection. Your code is vulnerable now.
Try adding error_reporting(E_ALL); near the beginning of your code. There is a good chance that a notice message will tell you what you're doing wrong.