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.
Related
We have an assignment for school and I've tried to build the application, however some text that I want to have inserted into a database doesn't get submitted.
I've tried different things, but the page does not show an error either.
This is the code of my insert page
<head>
</head>
<body>
<form action="index.php" method="post">
ID: <input type="text" name="id"><br/>
Server: <input type="text" name="Server"><br/>
Student: <input type="text" name="Student"><br/>
Docent: <input type="text" name="Docent"><br/>
Project: <input type="text" name="Project"><br/>
Startdatum: <input type="text" name="Startdatum"><br/>
Einddatum: <input type="text" name="Einddatum"><br/>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$con = mysqli_connect("localhost", "root", "usbw", "serverruimte");
if(!$con) {
die(mysqli_connect_error());
}
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
$result = mysqli_query($con, $sql);
if($result) {
echo "Opslaan voltooid!";
} else {
echo mysqli_error($con);
}
mysqli_close($con);
}
?>
</body>
</html>
Basically, what happens is: https://i.imgur.com/aUOx5yj.mp4
Does anyone know what the problem is and why the inserted data does not show up on the index page? The data does show on the page when I submit it directly into the MYSQL database.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
When working with MySQLi you should enable automatic error reporting instead of checking for errors manually. Checking for errors manually is a terrible practice, very error prone and should be avoided at all costs. Let MySQLi throw exceptions and do not catch them. See How to get the error message in MySQLi?
When opening MySQLi connection you must specify the correct charset. The recommended one is utf8mb4.
if (isset($_POST['submit'])) {
// Enable automatic error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create new instance of MySQLi class
$con = new mysqli("localhost", "root", "usbw", "serverruimte");
// Set correct charset. Important!
$con->set_charset('utf8mb4');
$stmt = $con->prepare('INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST['id'], $_POST['Server'], $_POST['Student'], $_POST['Docent'], $_POST['Project'], $_POST['startdatum'], $_POST['einddatum']);
$stmt->execute();
echo "Opslaan voltooid!";
mysqli_close($con);
}
Change this line:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
to:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('".$_POST['id']."','".$_POST['Server']."','".$_POST[Student]."','".$_POST['Docent']."','".$_POST['Project']."','".$_POST['Startdatum']."','".$_POST['Einddatum']."')";
Reason behind this change is because your query is wrong for the following reasons:
You were using strings instead of concatenating your real values coming from $_POST
Some of your indexes in $_POST were misspelled. For example:
$_POST[einddatum] should be $_POST['Einddatum']
Also, consider that this code is vulnerable to SQL Injection
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
This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 7 years ago.
I'm trying to prevent SQL injection using PDO, but I can't seem to connect. This is the working version - not SQL injection safe:
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
// Connect to database server
mysql_connect("localhost", "********", "********") or die(mysql_error());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// The SQL statement is built
$strSQL = "INSERT INTO mytable(name) VALUES('" . $_POST["name"] . "')";
// The SQL statement is executed
mysql_query($strSQL) or die (mysql_error());
// Close the database connection
mysql_close();
echo "Your name is " . $_POST["name"] ;
?>
</body>
</html>
This is working just fine. I read these pages on how to use PDO to protect against SQL injection attacks:
http://www.w3schools.com/php/php_mysql_connect.asp
http://www.w3schools.com/sql/sql_injection.asp
and wrote the following code following the guideline:
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
$servername = "localhost";
$username = "********";
$password = "********";
try {
$conn = new PDO("mysql:host=$servername, dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
echo "You have connected to the database server with PDO"
// The SQL statement is built
$stmt = $dbh->prepare("INSERT INTO mytable (name)
VALUES (:name)");
$stmt->bindParam(':name', $_POST['name']);
$stmt->execute();
// Close the database connection
mysql_close();
echo "Your name is " . $_POST["name"] ;
?>
</body>
</html>
But this code just gives me a blank page - no error message and nothing inserted into the database.
I also tried doing the connection as described in
http://www.stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
but the result was the same - a blank page without error messages.
What am I doing wrong?
You're using the wrong variable for $stmt = $dbh->prepare
which should be $conn and not $dbh as per your connection.
Having used error reporting, would have signabled an undefined variable dbh notice/warning.
You also can't use mysql_close(); with PDO as you are mixing APIs, which you can't do.
See Example #3 Closing a connection of "Connections and Connection" in the manual http://php.net/manual/en/pdo.connections.php
Another thing session_start(); is best to be above anything. You may be outputting before header.
Edit: You forgot a semi-colon in this line:
echo "You have connected to the database server with PDO"
which should read as
echo "You have connected to the database server with PDO";
which will break your code.
Error reporting would also have caught that syntax/parse error.
http://php.net/manual/en/function.error-reporting.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: Error reporting should only be done in staging, and never production.
I've tried looking for the problem but I can't seem to figure it out. The form shows with no errors, but on google chrome it just says "Server Error" when I try and submit the form.
<?php
if (empty($_GET["entries"])) //check if the admin entered # of weeks
{
?>
<p>How many weeks do you want to make? </p>
<form action="" method="get">
<input type="text" name="entries" placeholder="Number of weeks" />
<br/>
<input type="submit" name="submit_entries" />
</form>
<?php
}
else
{
//Second form
if (isset($_POST["submit"])) //check if submitted
{
//Process form
$entries=$_GET['entries'];
$newWeeks=$_POST['week'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$sql = "INSERT INTO onlineformdata (numberOfWeeks, newCampSessions) VALUES (" . PrepSQL($entries) . "," . PrepSQL($newWeeks) . ")";
mysql_query($sql);
if (mysql_query($sql) === FALSE) {
die(mysql_error());
}
mysql_close();
}
else //if not submitted yet, show the form
{
echo '<form action="" method="post">';
for ($count = 0; $count < $_GET["entries"]; $count++)
{
echo 'Enter a beginning to ending date for the week: <input type="text" name="week"><br/>';
}
echo '<input type="submit" name="submit"></form>';
}
}
?>
Maybe it's because I can't have the first form having an action pointing to itself (Where I'm using a method="get".
You don't appear to have defined the PrepSQL() anywhere. If that's the case you should be getting a fatal error, something like
Fatal error: Call to undefined function PrepSQL ...
Once that's fixed, if you're insert query is failing, it will probably be because of the values lacking enclosing quotes.
For future debugging you can turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Or you can just observe your server's error log. How that is done depends on the server setup so I suggest asking your host for directions.
Side note:
The mysql_* library is deprecated, consider upgrading to PDO or MySQLi
The use of a Prepared Statement is preferred to concatenating variables into your SQL.
So I have the following PHP code
<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$poscote = $_POST['postcode'];
mysql_real_escape_string($poscote);
//! Checks for direct access to page
if (empty($_POST)) {
header('location:index.php?nothingentered');
die();
}
require_once('../Connections/PropSuite.php');
mysql_select_db($database_Takeaway, $Takeaway);
$query_PC = "SELECT * FROM Postcodes WHERE pc = '$postcode'";
$PC = mysql_query($query_PC, $Takeaway) or die(mysql_error());
$row_PC = mysql_fetch_assoc($PC);
if( mysql_errno() != 0){
// mysql error
// note: message like this should never appear to user, should be only stored in log
echo "Mysql error: " . htmlspecialchars( mysql_error());
die();
}
else {
echo $row_PC['oc'];
}
?>
This is to process a form with the following code
<form action="search_postcode.php" method="post">
<input type="text" name="postcode" />
<button>Go</button>
</form>
Strangely its just showing a blank screen, no errors, nothing I have checked through and cannot seem to find a solution.
Many thanks in advance for your help.
As your $postcode variable is undefined, you are looking in your database for a row where pc is an error message.
That query could very well finish without errors, but it probably produces 0 rows, so you don't have an error, nor do you have a result. In that case you output nothing, so you will see a blank screen.
You probably want:
$postcode = mysql_real_escape_string($poscote);
instead of:
mysql_real_escape_string($poscote);
and put it below the database connection section.
Also, you should switch to PDO (or mysqli) and prepared statements to avoid sql injection problems and because the mysql_* functions are deprecated. Note that your mysql_real_escape_string does not do anything (except removing the contents of your variable...) when you don't have a database connection open.
In addition to the other answers, and without mentioning that you should be using PDO or mysqli, you could be having a character encoding issue. Try doing something like this:
define('DB_CHARSET', 'ISO-8859-1');
define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);
...
echo "Mysql error: " . htmlentities(mysql_error(), REPLACE_FLAGS, DB_CHARSET);
Replace the value of DB_CHARSET with whatever encoding your database is using. If you try to use htmlentities() with an invalid character it will produce an empty string.
As of php.net, to enable php errors using the ini_set, you have to do it like this
ini_set('display_errors', '1')
This is taken from this link