I'm making a small project and I'm having some trouble with a php script. Basically, when they enter the text then click 'Enter' It loads to the 'insert.php'. The thing is, if they just visit the insert.php page without going to the main page It enters a plan table which could cause big problems.
Code:
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Can you help me fix this problem as It could cause a lot of troubles.
First you need to validate your $_POST variables by using isset().
If they are not submitted from a form, $_POST will be empty. Meaning that when a user try to type in the url, there won't be any post data and your SQL queries won't run.
2nd, you are subject to SQL injection since you are not escaping the content.
I'd suggest escaping each variable by using a prepared statement or mysqli_real_escape_string (less secure but better than nothing).`
if ( isset($_POST) && !empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['age'])) {
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//simple example of escaping variables - BUT NOT AS SECURE AS PREPARED STATEMENT!!
$firstname = $con->real_escape_string($_POST['firstname']);
$lastname = $con->real_escape_string($_POST['lastname']);
$age = $con->real_escape_string($_POST['age']);
//With MySQLi it is best practice to use `prepere`, `bind_param` and `execute:
//or use PDO.
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$firstname','$lastname','$age')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
Lastly, you were missing the single quotes inside your $_POST variables.
Hope this helps!
This is pretty simple.
if(isset($_POST)):
//all of your code here
endif;
You have to check if $_POST exists to trigger your sql request
if (isset($_POST)){
//script
}
One of the first things that I see right off the top of my head is the fact that you are not checking to ensure that something has infact been typed Into your input box that passes the data to your other file. You can try to use isset() or array_key_exist(). Not to mention these are things that you should be doing anyway.
Related
I installed MySql on my Raspberry Pi 2 Model B+ a few days ago to see if I could use it, PHP, phpmyadmin, and Apache to make an accessible database to organize and catalog books that are around the house. I have a table in a MySQL database set up as a prototype with three columns; Booknumber (set to auto-increment), title, and authorLastName. I'm trying to use a form to insert books into table beta, in database bookProof.
Here's the code for the form:
<html>
<body>
<form action="catalog.php" method="POST">
<p>Book Title: <input type="text" name="title"></p>
<p>Author's Last Name: <input type="text name="authorlastname"></p>
</form>
</body>
</html>
Which links to "catalog.php", which is:
<?php
define('DB_NAME', 'bookProof');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Could not connect: " . $conn->connect_error);
}
$value = $_POST["title"]
$value2 = $_POST["authorlastname"]
$sql = "INSERT INTO beta ('title', 'authorLastName') VALUES ('".$value."', '".$value2."')"
$query = mysqli_query($conn,$sql);
if ($conn->($sql) === TRUE) {
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When demoform.php is opened, it functions normally, but when the "Add Books" button is clicked, it goes to catalog.php as intended, but the catalog.php page is blank, the table is unchanged, and Google Chrome's "Inspect" tool gives the error:
POST http://192.168.254.11/Library/catalog.php 500 (Internal Server Error) catalog.php:1
If anyone knows how to get the input to the database, please let me know.
Note: This is just a home system, so security is not a priority (I don't need SQL code injection protection).
Your note, "...security is not a priority (I don't need SQL code injection protection)" - you might think that, but you should do it anyways. Not only does it protect your database should your system be exposed (or made public at a later time), it will handle strings automatically for you, so that your query won't break if your strings have quotes ' in them.
One issue is that you're using singlequotes around column and table names. This should be backticks, or none at all. Then you were missing a semicolon ; after defining your $value, $value2 and $sql strings.
Then you're doing something a bit odd - which is also causing a parse-error (Had you enabled error-reporting and checked your logs, you'd see a "Parse error: syntax error, unexpected (" error in your logs), you're querying the table with mysqli_query(), but then you try to do it again - except you're trying to query on the querystring, and not the query method. Note the comments I've added in the code below.
// Don't use singlequotes ' for columns and table-names
// Use backticks ` - quotes are for strings
$sql = "INSERT INTO beta (`title`, `authorLastName`) VALUES ('".$value."', '".$value2."')"; // You were also missing a semicolon here!
// $query = mysqli_query($conn,$sql); // Remove this line, as you're attempting to query it twice
if ($conn->query($sql) === TRUE) { // You're missing the query() method here
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using prepared statements won't be that much of a difference, and you really should do it. There's absolutely no reason to not use prepared statements! Look how little changes that have to be made!
$sql = "INSERT INTO beta (title, authorLastName) VALUES (?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ss", $value, $value2);
$stmt->execute();
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You've also got some invalid HTML which would cause issues - the following line had a missing quote to close off the type attribute.
<input type="text" name="authorlastname">
I suggest you read the following documentation and articles
When to use single quotes, double quotes, and backticks in MySQL
How can I prevent SQL injection in PHP?
PHP manual on mysqli_stmt::bind_param
How to get useful error messages in PHP?
PHP Parse/Syntax Errors; and How to solve them?
As a final note, you should check that the form was submitted and that it has values before inserting into the database. Also, using variable-names like $value and $value2 are not really descriptive - you should avoid it and use proper names for your variables.
Have some problem I couldn't find solution for, though searched through many sources (and questions here too). So, here it is.
With the PHP-code below I suppose to collect data from a HTML-form and send it to a local WAMP-server. But, though final check shows me "Success!", no new rows in the database's table are found, it stays empty. Names are correct, commands are (as I see it) too, so I just don't know what's wrong.
I hope you guys could help me. ^^
//Check if user submited a form
if (isset($_POST['submit'])) {
//Check if from is properly filled
if (empty($_POST['itemName']) || empty($_POST['itemPic']) || empty($_POST['itemPrice']) || empty($_POST['itemProvider'])) {
echo '<script>alert ("Fill out the form please!")</script>';
} else {
$conn = new mysqli('localhost:3306', 'root', '', 'goods-review');
//Check if connection established
if (mysqli_connect_errno()) {
exit('Connect failed: ' . mysqli_connect_error());
}
//Sending data
$newItem = array('itemName' => $_POST['itemName'], 'itemPic' => $_POST['itemPic'], 'itemPrice' => $_POST['itemPrice'], 'itemProvider' => $_POST['itemProvider']);
$sql = "INSERT INTO goods (itemName, itemPic, itemPrice, itemDate, itemProvider) VALUES ('" . $newItem['itemName'] . "', '" . $newItem['itemPic'] . "', '" . $newItem['itemPrice'] . "', date('Y:m:d, H:i:s'), '" . $newItem['itemProvider'] . "')";
//Check if sent
if ($sql) {
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
$conn->close();
}
}
The code is just assigning a string value to a variable.
$sql = "INSERT ...";
And the string value is not submitted to the database; it's not being executed as a SQL statement. There's nothing magical about the name of the variable. As far as PHP is concerned, the code is just assigning a value to a variable. That's it.
If you want to execute a SQL statement, you need to add code that actually does that. It shouldn't be difficult to find an example of how to do that.
IMPORTANT NOTE: The code in the question appears to create a SQL statement that is vulnerable to SQL Injection. A much better pattern is to use prepared statements with bind placeholders.
Reference: mysqli_prepare
If there's some (unfathomable) reason that you can't use prepared statements, then at a minimum, any potentially unsafe values that are included in the SQL text must be properly escaped.
Reference: mysqli_escape_string
If you have setup the $newItem array first.
Normaly you will validate the user-input and ensure that the user-input has no SQL injections in it.
Read here about it: What is SQL injection?
After that
(You have to add $newItem['itemDate']=date('Y:m:d, H:i:s');)
$sql = "INSERT INTO goods (".implode(', ',array_keys($newItem)).")"
." VALUES ('".implode("', '",$newItem)."')";
if (mysqli_query($conn,$sql)){
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
If you are using this:
you dont have too keep an eye on the right field order
every field value becomes ' around them
you have less code to write
field count and order can change
Finally mysqli_query() returns FALSE if nothing is insert and you can check for that.
Sidenote: Try to use OOP Version of the MYSQLi Extention and Prepared Statments. Read about it here: mysqli, OOP vs Procedural
I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);
PHP Newbie here: Quick question on forms and php,
Form in Html page
<form class="form" id="form" onsubmit="return validateForm()" method="post" action="submitdatabase.php">
I can insert data into my database successfully but how do I direct them to a certain URL as well?
If it helps, below is my PHP, needless to say it doesn't work:
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES ('$_POST[fname]','$_POST[lname]','$_POST[address]','$_POST[phone]','$_POST[email]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con)
header("Location: URLREDIRECTION.com")
?>
PHP Newbie.. this should work
always use this to escape strings mysql_escape_string($var);
also mysql_connect() is depreciated, use mysqli_connect('host', 'user', 'password', 'database') instead.
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$fname = mysql_escape_string($_POST['fname']);
$lname = mysql_escape_string($_POST['lname']);
$address = mysql_escape_string($_POST['address']);
$phone = mysql_escape_string($_POST['phone']);
$email = mysql_escape_string($_POST['email']);
mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES
('$fname','$lname','$address','$phone','$email')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
header("Location: http://yoursite.com");
This code... is... a bit of a mess and old. First things first: don't use mysql_* functions. Also you must escape your user's data for sure. To simplify both in one, I will work with PDO. Here you have a tutorial (just click here). Also, as other stated, you also needed to close a couple of semicolons.
<?php
/* Create a PDO object */
$DB = new PDO("mysql:host=localhost;dbname=database",'root','');
/* Prepare the statement you want to do, in this case, an INSERT */
$con = $DB->prepare("INSERT INTO leads (fname, lname, address, phone, email)
VALUES (?,?,?,?,?)");
/* Execute the previous statement with the corresponding values for each '?' */
$con->execute(array($_POST['fname'],
$_POST['lname'],
$_POST['address'],
$_POST['phone'],
$_POST['email']));
/* Redirect the user */
header("Location: http://www.example.com/");
?>
Obviously this is not secure. The OP knows this and has chosen to do
things this way. If he genuinely wants to do things deliberately
wrong I have no problem with that.
Anyone else reading this answer should keep in mind that this is
horrible practice and I have only given it as an answer because it is
clearly what he wanted. Do not use this.
In an actual application, you should be at the very least using mysql_real_escape_string() to escape the $_POST variables from
user input, or (much) better yet, use MySQLi or PDO in conjunction
with prepared statements, to eliminate the chances of SQL injection.
You were missing a semicolon.
Also, you changed the header line instead of leaving somewhere you were trying to redirect to there. How are we supposed to debug a script that we can't even see? Try it as posted here and see if it takes you to google. If not then there's something else going on. If it does, you typed out the header() function wrong but we couldn't tell, because you didn't show it to us.
Try this:
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[address]','$_POST[phone]','$_POST[email]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
header("Location: http://www.google.com");
?>
Also, as a few people have pointed out already mysql() functions are officially depreciated. Although it should be working anyway.
try this..this will work 100%
<?php
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$phn=$_POST['phn'];
$email=$_POST['email'];
$street=$_POST['street'];
$city=$_POST['city'];
$state=$_POST['state'];
$con=mysqli_connect('localhost','root','','database');
$insert= "INSERT INTO table (id,name,phone,email,street,city,state) VALUES('','$fname $lname','$phn','$email','$street','$city','$state')";
$run=mysqli_query($con,$insert);
if($run)
{
header('location:https://google.com');
}
?>
You have a syntax error here:
mysql_close($con)
You need to add a semicolon:
mysql_close($con);
If your script produces any output before the header() statement, the redirect will not happen. Warnings, errors, and intentional output will all cause your header() statement to fail.
If you are redirecting to another site, consider use the 'http://' or 'https://' prefix for clarity:
header("Location: http://urlredirection.com");
If you are redirecting to your own site, just use a leading slash:
header("Location: /your/url.php");
Finally, consider updating your code to use mysqli or PDO instead of the deprecated mysql_* functions.
I post the data of dynamically generated textbox in PHP. When I post the data using real_escape_string(), i.e:
$ingredient = mysql_real_escape_string($_POST['ingredient']);
...it doesn't post data from textbox and I use simple $_POST['']; method i.e:
$ingredient = $_POST['ingredient'];
...it gives me error when I use a single quote (') in my text.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's', 'fgad', '55')' at line 2
this was my old post i solved the problem locally by enabling magic_quotes_gpc = On but when upload this on my server it does't work again so how can i turn on magic quotes on server.
Do you have an open database connection? mysql_real_escape_string needs a MySQL server to talk to in order to function.
You might want to try
$ingredient = $_POST['ingredient'];
$ingredient = mysql_real_escape_string($ingredient);
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
you must used connection db see
http://php.net/manual/en/mysqli.real-escape-string.php
you can use also
string mysqli::real_escape_string ( string $escapestr )
I think this might be related to the "magic" quotes feature -- see this page for details: Magic Strings & SQL
Basically, because of problems with SQL injection attacks, they pre-escaped strings with quotes after a certain version of PHP (I think it was 5.0, but I could be wrong). So the end result is that now your software has to check for the software version and behave differently depending on whether the string is already escaped or not.