I would like a user to be able to insert a "bid" into a MySQL table using a php form - this is only for demo, not live purpose. I get the following error message,
Error: 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 ''90','2011-07-13'' at line 3 (Line 3 refers to my tag?) I figure it doesnt like the form inputs just being "text" type, but no idea how to fix it - all advice very welcome, this is my form & php code below;
<form action="insert.php" method="post">
<div><label for="commodity">Commodity</label><input type="text" name="commodity"/></div>
<div><label for="region">Region</label><input type="text" name="region"/></div>
<div><label for="member">Member</label><input type="text" name="member" /></div>
<div><label for="size">Size</label><input type="int" name="size" /></div>
<div><label for="price">Post Bid</label><input type="decimal" name="price" /></div>
<div><label for="posted">Date Posted</label><input type="text" name="posted"/></div>
<P><label for="submit">Submit Bid</label><input type="submit" /></P>
</form>
& php
<?php
$con = mysql_connect("localhost","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("palegall_newTrader", $con);
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]'";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Many thanks in advance, scotia
You're vulnerable to SQL injection, and your POST probably contains a ', which is causing the syntax error. Try the following:
$commodity = mysql_real_escape_string($_POST['commodity']);
$region = mysql_real_escape_string($_POST['region']);
etc...
$sql = "INSERT INTO ... VALUES ('$commodity', '$region', etc...)";
the escape function will ensure that any SQL metacharacters in the data are escaped, so they can't "break" your query. Never EVER directly insert user-provided data into an SQL query, even if it's a simple script that only you will ever use. Get into the habit of escaping everything (or better yet, using PDO prepared statements), because at some point, you'll get burned if you don't.
Your closing parenthesis need to go after the last value to be inserted, now it's after the 4th element. Put it at the and of the statement.
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')"
Also, follow #Marc's advice and sanatize your input.
Shouldn't it be
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted) VALUES ('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')";
There is a misplaced parenthesis after $_POST['size'] that should be after $_POST[posted]
The SQL should look like this:
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')";
Related
Edit: Error: Column count doesn't match value count at row 1
I have been trying for a long time now (hours if not days with multiple attempts) to set up a prepared statement to stop SQL injection attacks and I just cannot get my head around it. Could someone help me out with this and point out where I have went wrong? I want to learn how to do this so I can use it in future but at this rate I will never get it.
The form:
<form action="php/xaddPlayerSkills.php" method="post"> <!--player skills form to be added-->
playerID : <input type="int" name="playerID" value="<?php echo $playerID ?>" readonly> </td></tr>
SquadID: <input type="text" name="squadID"><br>
Passing: <input type="text" name="passing" value="Standard: Spin: Pop:"><br>
Tackling: <input type="text" name="tackling" value="Front: Rear: Side: Scrabble:"><br>
Kicking: <input type="text" name="kicking" value="Drop: Punt: Grubber: Goal:"><br>
Comments: <input type="text" name="comments"><br>
Date: <input type="date" name="date"><br>
<input type="Submit" value = "Add ">
</form>
This is my processing page:
<?php session_start(); include('functions.php');
$sheetNo="";
$playerID=$_POST['playerID'];
$squadID=$_POST['squadID'];
$passing=$_POST['passing'];
$kicking=$_POST['kicking'];
$tackling=$_POST['tackling'];
$comments=$_POST['comments'];
$date=$_POST['date'];
/* Use for error testing - Uncomment to check variable values when executed
ini_set('display_errors', 'On'); ini_set('html_errors', 0); error_reporting(-1);
print_r($_POST); */
//sets up and executes the connection using the information held above
/* THERE IS CONNECTION INFORMATION HERE BUT I HAVE REMOVED IT AS IT IS CREDENTIALS */
$con=mysqli_connect($host,$user,$userpass,$schema);
// Error handling: If connection fails, the next lines of code will error handle the problem and if possible, give a reason why.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= mysqli_query($con,"INSERT INTO playerSkills VALUES (playerID,squadID,passing,tackling,kicking,comments,date)");
$insert=$con->prepare($result);
$insert->bind_param("isssssd",$playerID,$squadID,$passing,$tackling,$kicking,$comments,$date);
$insert->execute();
$insert->close();
mysqli_close($con);
header ("location: ../databasePlayers.php");
?>
You have a couple of problems in your code, but the most notable is the placeholders in the query, which should ?'s instead of things like VALUES (playerID,squadID,passing,tackling,kicking... and that you're using a type double, d, to describe a date:
$con=mysqli_connect($host,$user,$userpass,$schema);
// Error handling: If connection fails, the next lines of code will error handle the problem and if possible, give a reason why.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= "INSERT INTO playerSkills VALUES (?,?,?,?,?,?,?)";
$insert=$con->prepare($result);
$insert->bind_param("issssss",$playerID,$squadID,$passing,$tackling,$kicking,$comments,$date); // change d to s for the date
$insert->execute();
$insert->close();
Read the docs for clarification on the data types. d is for doubles, not dates. Then look at the examples for what you should use as placeholders.
EDIT: Caution - if one of these columns is an AUTO INCREMENT column you should not include it in the query as the database will take care of making sure the column is updated properly.
I'm trying to insert some data to my database, but it will only insert
an unique id and userid. Rest of the attributes wont follow. Any suggestions?
Image of insert:
<?php
if(isset($_POST['project']))
{
// Escape user inputs for security
$stripped = mysql_real_escape_string($_GET['id']);
$title = mysqli_real_escape_string($_POST['title']);
$about = mysqli_real_escape_string($_POST['about']);
$code = mysqli_real_escape_string($_POST['code']);
mysql_query("INSERT INTO cms_prosjekt (userid, title, about, code) VALUES
('".$_SESSION['user']['id']."', '".$title."', '".$about."', '".$code."')") or die(mysql_error());
}
?>
HTML
<form action="" method="post">
<input type="text" class="form-control" type="text" name="title" id="title" placeholder="Fullt navn" style="margin-bottom:10px">
<input type="text" class="form-control" type="text" name="about" id="about" placeholder="Kode bedrift" style="margin-bottom:10px">
<input type="text" class="form-control" type="text" name="code" id="code" placeholder="Passord" style="margin-bottom:10px">
<button type="submit" name="project" class="button" class="btn btn-success" style="margin-bottom:10px;">Register prosjekt nĂ¥</button>
</form>
you need to provide the $link argument which is your connection to properly escape your values.
mysqli_real_escape_string ( mysqli $link , string $escapestr )
Seeing your code and that it only enters one value, this tells me you are using the mysql_ API to connect with, and you're mixing those with mysqli_real_escape_string(), and requires a db connection for it and as the first argument.
Since $stripped = mysql_real_escape_string($_GET['id']); is all that is getting entered in db, after seeing your screenshot.
Those different APIs do not intermix. You need to use the same one from connecting to querying.
In your case, that would be mysql_* - mysql_real_escape_string().
I suggest you start using a prepared statement right away.
https://en.wikipedia.org/wiki/Prepared_statement
Note: Using mysql_real_escape_string() doesn't fully protect against an SQL injection. Read the following Q&A on the subject;
SQL injection that gets around mysql_real_escape_string()
Footnotes:
The MySQL_ API has been removed as of PHP 7.0. Should your server eventually get upgraded to it, you will no longer be able to use your present code.
It's time to switch over to either using the MySQLi_ or PDO API and with a prepared statement.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/pdo.prepared-statements.php
You should also check for any empty fields. Just an isset() against your submit button isn't enough.
If your site is live or will be live soon, someone may enter empty values and could trigger errors or insert empty values in your database, which I'm sure you're not going to appreciate.
Reference:
http://php.net/manual/en/function.empty.php
You have used both mysqli and mysql it should be anyone of them.
if (isset($_POST['project'])) {
$stripped = mysql_real_escape_string($_GET['id']);
$title = mysql_real_escape_string($_POST['title']);
$about = mysql_real_escape_string($_POST['about']);
$code = mysql_real_escape_string($_POST['code']);
mysql_query("INSERT INTO cms_prosjekt (userid, title, about, code) VALUES ('" . $_SESSION['user']['id'] . "', '" . $title . "', '" . $about . "', '" . $code . "')") or die(mysql_error());
}
Hello dear why i always fail to learning php, would be grateful if someone can help me. :'(
i was followed step by step here :
http://www.w3schools.com/php/php_mysql_insert.asp
but when i click button submit query nothing happen, just show a blank white screen and i dont see new data on database?
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
<?php
$con=mysqli_connect("localhost","root","","garutexpress");
// 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);
?>
if data successfull added it should give
echo "1 record added"; but i never see this message.
Your table name is "persons", not "Persons"
When you make a query, your table name has to be the same as in your database. If you look in phpMyAdmin , your table is "persons" with lowercase
Edited according to :
#I Can Has Cheezburger
Please change the name of your table in your code like and make sure about to wrap quotes accordingly :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// 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);
?>
Common error, you are not wrapping your POST array index with quotes.
Do it like:
$sql='INSERT INTO persons (FirstName, LastName, Age)
VALUES
("'.mysqli_real_escape_string($con,$_POST['firstname']).'","'.mysqli_real_escape_string($con,$_POST['lastname']).'","'.mysqli_real_escape_string($con,$_POST['age']).'");
Also, as #seblaze mentioned, table names are case-sensitive, so use persons instead of Persons
For more security, use prepared statements.
A blank screen means most of the time that you are dealing with some error. You have to turn error reporting on for your local development.
How do I enable error reporting in PHP?
Check that your column names are written camelCase in your script but not in your database.
In most cases it's handy to have an ID column which is your unique identifier.
Good practice: Start using PDO
First,
You need to update the PHP configurations as:
memory_limit = 64M
Make sure you increase the memory .
Then, you need to enable Error reporting, using .htaccess file or configure it with php.ini. Read this for help
After that you can debug your work.
Try the code in this,
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
in w3schools it uses mysqli I also had some issues with it.
in the link it has some sample codes and it uses mysql
I have created an SQL database using ProgreSQL with Heroku for my Facebook web app, the following code is the form to collect the data
</style>
<div class="container">
<form action="insert.php" method="post" onSubmit="window.location.reload()">
Cover URL: <input type="text" name="Cover URL" id="coverURL"><br><br>
Title: <input type="text" name="Title" id="title"><br><br>
Author: <input type="text" name="Author" id="author"><br><br>
Genre:<br> <select name="genre" id="genre">
<option>Adventure & Action</option>
<option>Anthologies</option>
<option>Classics</option>
<option>Sport</option>
<option>War</option>
//More options in actual code, just deleted some to save space.
</select><br><br>
Total Pages: <input type="number" name="TotalPages" id="totalpages"><br><br>
Curent Page: <input type="number" name="CurrentPage" id="currentpage"><br><br>
<input type="submit"> </form><br><br></div>
</center>
</section>
That then calls insert.php
<?php
$dbconn = pg_connect("host=ec2-54-243-190-226.compute-1.amazonaws.com port=5432 dbname=d6fh4g6l0l6gvb user=[REMOVED] password=[REMOVED] sslmode=require options='--client_encoding=UTF8'")
or die('Could not connect: ' . pg_last_error());
pg_query("INSERT INTO books(coverURL, title, author, genre, currentPg, totalPg) VALUES('"$_POST["coverURL"]"','"$_POST["title"]"','"$_POST["author"]"','"$_POST["genre"]"', '"$_POST["currentpages"]"','"$_POST["totalpages"]"')");
pg_close($dbconn);
?>
The problem is I get error 500 when I hit submit, after looking around online most solutions say there must be an error in the PHP, but due to my inexperience (learning this as I go) I have no idea what I've done wrong.
I can provide more information if necessary. Thanks in advance!
Try this:
Please make sure the names of the html inputs match the $_POST values.
mysqli_query($con,"INSERT INTO books(coverURL, title, author, genre, currentPg, totalPg) VALUES('".$_POST["coverURL"]."','".$_POST["title"]."','".$_POST["author"]."','".$_POST["genre"]."','".$_POST["currentpages"]."','".$_POST["totalpages"]."')");
EDIT: use this statement ------^
And instead of:
'$_POST[author]'
It is better to do them like this:
'".$_POST["author"]."'
And also are you aware that $sql isnt actually being inserted into the db?
An error 500 is a "internal server error". This basically means that something on the server side has failed, it's just a very generic error message. Basically it can be everything, it's not only limited to your script. It could be a Apache module error or anything else that refuses your WebServer software to handle the request without any fatal failures.
If it only occurs on the same actions (like submitting a form or calling a special page) it's very likely it's a script error causing the error 500.
You should look up your log files, esp. the apache error log. It should contain further informations on what has gone wrong.
In your case, maybe your sever is not allowed to connect to an external database server, but it's only a guess.
The problem is that you're really "mixing" things together. Your code connects with pg_connect and querying with mysqli. Use only Postgree functions to connect to the database Read manual at http://www.php.net/manual/en/ref.pgsql.php.
I would do something like: (I have not tested it though)
<?php
$dbconn = pg_connect("host=ec2-54-243-190-226.compute-1.amazonaws.com port=5432 dbname=d6fh4g6l0l6gvb user=[REMOVED] password=[REMOVED] sslmode=require options='--client_encoding=UTF8'") or die('Could not connect: ' . pg_last_error());;
$coverUrl = $_POST["coverURL"];
$title = $_POST["title"];
$author = $_POST["author"];
$genre = $_POST["genre"];
$currentPages = $_POST["currentpages"];
$totalPages = $_POST["totalpages"];
pg_query_params($dbconn, "INSERT INTO books(coverURL, title, author, genre, currentPg, totalPg) VALUES($1,$2,$3,$4,$5,$6)", array($coverUrl, $title, $author, $genre, $currentPages, $totalPages));
pg_close($dbconn);
?>
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database. I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.
Here's the latest version of the code. Could someone please tell me what I am doing wrong?
* Basic HTML Form *
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
* Processor File *
<?php
$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
{die('Could not connect to database: ' . mysql_error());}
mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
Print "Your metrics have been successfully added to the database.";
mysql_close($con);
?>
Your mysql-syntax is wrong.
Try
INSERT INTO my_metrics
SET
date = '$date',
metric1 = '$metric1',
metric2 = '$metric2'
Depending on what the table looks like, your code may or may not work,
"INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')"
assumes that the fields are in that order, and that there are no fields before this one.
"INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')"
would be more future proof, and may also solve your problem as they are going to insert into the correct fields.
It is also possible that you are getting some bad data for the field definitions, try doing the insert in phpmyadmin or at the command line instead of in php, then work backwards from there.
As far as the vulnerability to SQL injection, you should feed your input strings to mysql_real_escape_string();. This will escape any unwanted characters.
When connecting to the database, you write
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
You can simplify this, and making this more readable by writing
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql:<hr>'.mysql_error());
For solving your problem, see if specifieng column names helps. If you don't, mysql will assume you enter values in the order of the columns, you might get some trouble with an ID field, or something like that. Your query could look like this:
"INSERT INTO my metrics (date,metric1,metric2) VALUES ('$data','$metric1','$metric2'))"
And finally, here's a speed concideration.
There are two ways to write strings: using single quotes ('string'), and using double quotes ("string"). in the case of 'string' and "string", they will work exactly the same, but there is a difference. Look at the following code
$age=3
echo 'the cat is $age years old.';
//prints out 'the cat is $age years old.'
echo "the cat is $age years old.";
//prints out 'the cat is 3 years old'
echo 'the cat is '.$age.' years old';
//prints out 'the cat is 3 years old'.
As you can see from this example, when you use single quotes, PHP doesn't check the string for variables and other things to parse inside the string. Doing that takes PHP longer than concatinating the variable to the string. so although
echo "the cat is $age years old"
is shorter to type than
echo 'the cat is '.$age.' years old';
it will boost your page loading when you write larger applications.
Hooray! Hooray! Hooray!
Thank you all for such helpful advice! It finally works! Here's the updated code in case any other newbies have the same issue. (Hope I didn't screw anything else up.)
Form
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
Processor
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
// 1. Create connection to database
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("my_metrics") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$date=mysql_real_escape_string($_POST['date']);
$metric1=mysql_real_escape_string($_POST['metric1']);
$metric2=mysql_real_escape_string($_POST['metric2']);
// 4. Insert data into table
mysql_query("INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>
Here you go love :) try W3c it a good place for new pepps
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO my_metrics (date, metric1, metric2)
VALUES
('$_POST[date]','$_POST[mertric1]','$_POST[metric2]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your metrics have been successfully added to the database.";
mysql_close($con)
?>