I am trying to post data to my database using the following code:
<?php
if(isset($_POST['add']))
{
$dbhost = 'internal-db';
$dbuser = 'support';
$dbpass = 'sgh';
$db = "mpc";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$country = $_POST['country'];
$message = $_POST['message'];
$callback = $_POST['callback'];
$sql = "INSERT INTO enquiries
(firstname, surname, email, phone, country, message, callback)
VALUES('$firstname','$surname', $email, $phone, $country, $message, $callback)";
mysql_select_db($db);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
When I try to post the form I revieve the following error:
Could not enter data: 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 ' , , , )' at line 3
Can't work out what is wrong in the code. Can you help???? Am I using deprecated code??
The variables in your query are empty ($email, $phone, $country, $message, $call). Try to do var_dump of the variables before the query and see if they have some value. Also you need to wrap them with quotes like '$var' when they are strings, such as a mail.
Also, for the love of god, sanitize the input. See here:
What are the best PHP input sanitizing functions?
How can I prevent SQL injection in PHP?
You have to put the single quote around the string columns even if they are blank or contain value.
$sql = "INSERT INTO enquiries
(firstname, surname, email, phone, country, message, callback)
VALUES('$firstname','$surname', '$email', '$phone', '$country', '$message', '$callback')";
Do not forgot to use mysql_real_escape_string on the data.
You haven't encapsulated your fields in quotes. E-mail address (amongst others) without quotes will make your INSERT statement invalid.
Besides that, you should always escape the input, because the input can contain invalid characters, or worse, it can contain malicious code that may destroy your data!
So:
if (array_key_exists($_POST, 'email')) {
$tmpemail = (string)$_POST['email'];
// Optional additional checks for pattern matches go here..
// if all tests succeed, escape special characters and assign value:
$email = mysql_real_escape_string($tmpemail);
}
// Similar checks for other values
if ((isset($email) && isset($fielda) && isset($fieldb) ... )
{
$query = "
INSERT INTO YourTable(fielda, fieldb, email, ...)
VALUES('valuea', 'valueb', '$email', ...)";
}
else
{
// Some values missing. Handle appropriately.
}
Related
I am doing php and writing some code to insert data into different tables at the same time. I wrote a foreach loop and one part of my code is as follows:
while ($datarow = dbgetrow($dataresult)) {
if ( $dotcount > $datanumrows) {
showarchivestatus(" .", true);
$dotcount = 1;
}
$sqlvalues = "";
You need to escape your string before putting it into the database.
Here is a basic example of how to do it in MySQLi
<?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);
?>
Here is an example of PDO:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>
You may want to consider using a prepared statement. There are several benefits to this including:
Security - Helps prevent SQL injection
Speed - You only are sending the values.
http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Sources:
http://www.w3schools.com/php/func_mysqli_real_escape_string.asp
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/pdo.quote.php
I am having a little difficulty in saving values via the URL into a SQL database. I can explicitly put in values into the the INSERT command, but that is not what I want.
Say I had a URL like the following:
and code like the following:
<?php
include 'curr.php';
$url = curPageURL();
$query_str = parse_url($url, PHP_URL_QUERY);
$query = parse_str($query_str, $query_params);
$fn = $_REQUEST['Firstname'];$sn = $_REQUEST['Surname'];
$link = mysql_connect('server.co.li', 'username', 'pass333');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'INSERT INTO p_database '.
'(Firstname, Surname) '.
'VALUES ($fn, $sn)';
mysql_select_db('my_db');
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($link);
?>
I have tried $_Get and $_POST as well as $_REQUEST to get the information, and here is the error that is produced when I run:
"Connected successfullyCould not enter data: Unknown column '$fn' in 'field list'"
Any assistance would be appreciated.
(P.s. I know the code is not secure or safe, that will come after the functional parts are complete).
Your quotes are incorrect,
$sql = "INSERT INTO p_database ".
"(Firstname, Surname) ".
"VALUES ('$fn', '$sn')";
Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You need to escape your $fn and $sn like so:
$sql = "INSERT INTO p_database (Firstname, Surname) VALUES ('$fn', '$sn')";
I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.
Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.
you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");
CODE UPDATED, STILL NOT WORKING.
I know I´m apparently using mysql function which will be outdated. But for now all I want is for this code to work. I want to know what I´m doing wrong:(
I´m very new to php and databases... I have been struggling to get simple html form data to go into the database table. And I just can´t get it to work:( Can anyone help and see what is wrong with my code? I´ve just done a simple table in the database with the fields ID, FIRSTNAME and SURNAME.
Here is the code:
<?php
//connect to database
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_db = 'test';
if (!mysql_connect ($mysql_host, $mysql_user, $mysql_pass)||!mysql_select_db ($mysql_db) ) {
die(mysql_error());
}
// Code
if (isset($_POST['firstname'])&&
isset($_POST['surname'])) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
if (!empty($username)&&!empty($password)) {
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
/*$query = "INSERT INTO `test`.`test_tabell` VALUES (``, `.$firstname.`, `.$surname.`)"; */
$query_run = mysql_query($query);
if (!$query_run) echo mysql_error();
}
}
?>
<form action="add.php" method="POST">
Firstname:<br> <input type="text" name="firstname" value="<?php if (isset($firstname)) { echo $firstname; } ?>"><br><br>
Surname:<br> <input type="text" name="surname" value="<?php if (isset($surname)) { echo $surname; } ?>"><br><br>
<input type="submit" value="Submit">
</form>
Thank you!
Don't use mysql specific syntax, It's outdated and it begins to be annoying when you need to do some high level stuff, and you can't switch to sqlite or postgresql.
I recommend using PDO, you can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables (I think you forgot to define the name of the database);
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$GLOBALS['db'] = connectToDataBase($host , $databaseName, $user, $pass);
Now you have an instance of a PDO database donnection.
One thing I want to point out is that you're vonurable to sql injections, you want to use prepared statements in your query, like:
$query = "INSERT INTO test(first_name, sur_name) VALUES (:firstname, :surname);";
Where we will execute two variables $firstName and $surName on the query, making them replace the values of :firstName and :surName, let me show you by first creating a simple insertion function:
function insertFunction($db, $query, $firstName, $surName)
{
$statement = $db->prepare($query);
return $statement->execute(array(":firstName" => $firstName, ":surName" => $surName));
}
So It's easy for you to do something like
$firstName = 'Smith';
$surName = 'John';
$db = $GLOBALS['db'];
$success = insertFunction($db, $query, $firstName, $surName);
Now you can check if it was successful or not, by checking whether $success is true or false.
If you want to see more advanced use of PDO (multiple rows etc) then you can check out one of my comments here: Javascript function as php?
(Not the top comment).
I hope this helps. Please comment if anything is odd.
Hard to tell without seeing your schema but try this:
$query = "INSERT INTO `test`.`test_tabell` VALUES ('', '$firstname', '$surname')";
$query_run = mysql_query($query);
You're using backticks instead of apostrophes. Also, you're trying to execute a query before defining what the query is.
Your insert query is wrong and also open to SQL injections. Here's how it should be:
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
Notice the changing of all backticks to apostrophe.
Also, you're trying to execute the query before defining it.
EDIT
As per your information related to table definition, you can skip the id field from your table. The INSERT query will become:
$query = "INSERT INTO `test`.`test_tabell` (`FIRSTNAME`, `SURNAME`)
VALUES ('" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
$query_run = mysql_query( $query );
As posted in the comments, you REALLY SHOULD NOT use/learn/practice using any function that starts with "mysql_" since it will NOT work as soon as PHP is updated. These functions are on their way out. Best of luck with learning to use PHP and SQL databases - just make sure you're learning something that will be useful in the future. Make sure to read up on Object Oriented Programming (OOP) in relation to PHP and both the PDO and mysqli_* functions.
This one has got me stumped. When I try to save something to the database that contains an apostrophe ('), it will save the sence up until then and after that it does not not. For example;
Say I am trying to save this: Report details Tim Cook's changes at Apple, for better or worse »
It saves: Report details Tim Cook
It saves to the database fine but only everything before the '
My code:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Any help as to why it might not be saving properly? I have tried mysql_real_escape_string but (if I am using it correctly) that does not seem to work.
Side note: What is the best way to secure the form above from attacks?
Update It is also doing it for " as well.
You need to call mysql_real_escape_string() after connecting to your database:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Change
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
to
$query = "INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')";
echo $query;
mysql_query($query);
And check out the actual query you are sending, easy to spot the problems then :)