This is my code:
function function() {
$isbn = $_REQUEST["isbn"];
$price = $_REQUEST["price"];
$cond = $_REQUEST["cond"];
$con = mysql_connect("localhost","my_usernam", "password");
if (!$con) die('Could not connect:' . mysql_error());
mysql_select_db("my_database",$con);
$sql="INSERT INTO 'Books' (isbn, price, condition)
VALUES ('$isbn','$price','$cond')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
return "It works";
But when run it results in:
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 ''Books' (isbn, price....
Anyone know why this is happening?
You should use backticks instead of single quotes for table and field names:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('$isbn','$price','$cond')";
will work.
ps. to prevent all kinds of nasty security holes, escape the input fields with:
$isbn = mysql_real_escape_string($_REQUEST["isbn"]);
// etc etc for all fields
Wrap table names in backticks, not quotes, and make sure to escape your input for security:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('" . mysql_real_escape_string($isbn) . "',
'" . mysql_real_escape_string($price) . "',
'" . mysql_real_escape_string($cond) . "')";
Related
I have a prepared mysqli insert statement but when I try to insert data with quotes or double quotes I get this error: Prepare failed: (1064) 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 'Ask me in six months.' We don’t have six months to wait," he said. "I have a p' at line 1
when I use mysqli_real_escape_string around my text that I am trying to insert, it inserts into my database as empty data.
Is there a better way to handle single or double quotes? Or is there something wrong with my code?
$connection = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!($stmt = $connection->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES ('" . $title . "', '" . $date . "', '" . $preview . "', '" . $description . "','" . $image . "', '" . $detailImage . "', " . $showDetailedImage . ")"))) {
echo "Prepare failed: (" . $connection->errno . ") " . $connection->error;
}else{
$stmt->execute();
echo 'Press has been added <br>';
}
I have tried with mysqli_real_escape_string($title), mysqli_real_escape_string($preview) & mysqli_real_escape_string($description), but like I said it would insert it to the database as empty strings :(
As Micheal said in his comment
Since you're using mysqli with prepare() & execute() you'll be better off harnessing bind_param()
$stmt = $mysqli->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssss', $title, $date, $preview, $description, $image, $detailImage, $showDetailedImage);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
The above is just an example, I don't know what your database schema/structure looks like
Breakdown:
s means string.
d means double.
You can read more on the types (i, s, d, b) in the bind_param link above.
This php is suposed to send five attributes {id, description, email, price, shape} to the sales table in the salesinformation database.
<?php
define('DB_NAME', 'salesinformation');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Cannot connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Cannot use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['description'];
$value2 = $_POST['email'];
$value3 = $_POST['price'];
$value4 = $_POST['shape'];
$sql = mysql_query("INSERT INTO sales (id, description, email, price, shape) VALUES ('', '$value', '$value2', '$value3', '$value4')");
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
mysql_close();
?>
If I echo $value it prints out the correct information that I filled in my html form (So the part that extracts values from the HTML is working atleast). I run xampp and created the database with PhpMyAdmin, and when this PHP runs all I get is Error: Query was empty and nothing is added to the database at all.
What makes the mysql_query empty?
EDIT: I had missed a ' sign at one of the values.
Now instead I get this 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 '1' at line 1
Question: What makes the mysql_query empty?
It's you, who calls mysql_query without a real query:
$sql = mysql_query("INSERT INTO sales (id, description, email, price, shape) VALUES ('', '$value', '$value2', '$value3', '$value4')");
if (!mysql_query($sql)){ // <---- look here
die('Error: ' . mysql_error());
}
What we see in your code is that you pass $sql to mysql_query which isn't a valid query and you can check it with var_dump($sql);
Remove the ID column from your query. Assuming you made made it a INDEX (and AUTO_INCREMENT) probably:). You can either remove it out the fieldlist, or instead of the '' put a NULL there :).
Thanks for your help, let me know if you need anything else.
details in the title.
<?php
$subject = $_POST['subject'];
$comment = $_POST['comment'];
$submit = $_POST['submit'];
if ($submit)
{
$connect = mysql_connect("host","un","psw");
mysql_select_db("rebeler_comment");
$query = mysql_query("INSERT INTO table VALUES('','$subject','$comment')");
}
?>
<form action="form.php" method="POST">
<label>Subject</label></br>
<input type="text" name="subject"</br>
<label>Comment</label></br>
<textarea name="comment"></textarea></br>
<input type="submit" name="submit" value="Submit">
updated with my html
Firstly, the use of MySQL_ is deprecated. Use MySQLi_ and/or PDO.
Now, you're not specifiying "where" to put your data in your table.
Assuming your columns are named subject and comment respectively.
Also, the word table is a reserved word. Therefore if your table is indeed called table, you need to wrap in inside back ticks,
like this: `table`
$query = mysql_query("INSERT INTO table (`subject`, `comment`)
VALUES ('$subject','$comment')");
If table name is called "table":
Use:
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`)
VALUES ('$subject','$comment')");
Deleted '', from ('','$subject','$comment') because you only have 2 values going in DB.
You may even want to concatenate such as:
VALUES ('" . $subject . "','" . $comment . "')");
To echo a success message:
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`)
VALUES ('$subject','$comment')");
echo "Data successfully written to DB";
}
else{
echo "Sorry, there was a problem.";
}
EDIT 2:
<?php
$subject = $_POST['subject'];
$comment = $_POST['comment'];
if(isset($_POST['submit']))
{
$connect = mysql_connect("host","un","psw");
mysql_select_db("rebeler_comment");
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`) VALUES ('" . $subject . "','" . $comment . "')");
$retval = mysql_query( $query, $connection ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); }
echo "Entered data successfully\n";
mysql_close($connection);
}
?>
EDIT 1:
$query = mysql_query("INSERT INTO `table` (`subject`, `comment`) VALUES ('" . $subject . "','" . $comment . "')");
$retval = mysql_query( $query, $connection ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); }
echo "Entered data successfully\n";
mysql_close($connection);
Fix your SQL insert (among some things), define the columns to insert into, instead of blindly throwing stuff into the dark.
Ex:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Also use mysql_error() for get errors. I would also suggest leveraging a php framework to get around injection issues and other stuff you might miss doing mysql by hand.
I have this piece of code
<?php
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tables", $con);
$sql="INSERT INTO customer (Name, Telephone, Email, Address, PostCode, Specialisation )
VALUES
($_POST['firstname'], $_POST['telephone'],$_POST['email'], $_POST['address'],$_POST['postcode'],$_POST['special'])";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Inserted into Worker database";
mysql_close($con);
?>
I keep getting this error- Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in.
I am not sure what else to do. Please help. Thanks
You have several issues.
First, string values you're inserting into the database need single quotes around them.
Second, array variables in strings need to be wrapped in {} (i.e. $string = "Something something {$_POST['variable']}..."; to help the PHP parser figure them out.
Third, this code (once working) is massively vulnerable to hacking via SQL injection. Consider using PDO and prepared statements (as the mysql_* functions are being deprecated), or at the very least run user input through mysql_real_escape_string().
$sql="INSERT INTO customer (Name, Telephone, Email, Address, PostCode, Specialisation) VALUES ('" . mysql_real_escape_string($_POST['firstname']) . "', '" . mysql_real_escape_string($_POST['telephone']) . "', '" . mysql_real_escape_string($_POST['email']) . "', '" . mysql_real_escape_string($_POST['address']) . "', '" . mysql_real_escape_string($_POST['postcode']) . "', '" . mysql_real_escape_string($_POST['special']) . "')";
Fourth, you really shouldn't use the database's root user to connect.
Change your $sql variable to read on one line and to send the proper format to SQL:
$sql="INSERT INTO customer (Name, Telephone, Email, Address, PostCode, Specialisation ) VALUES ({$_POST['firstname']}, {$_POST['telephone']},{$_POST['email']}, {$_POST['address']},{$_POST['postcode']},{$_POST['special']})";
That should correct the PHP error of unexpected T_ENCAPSED_AND_WHITESPACE but you will need more corrections to fix the SQL Injection possibility.
I'm trying to insert a value into my sql table that has html in it: like follows
<?
$story ="<div class='post'><p class='date'>$mont<b>$day</b></p><h2 class='title'>lkjljt</h2><p class='meta'><small>Posted $name | $school, $date | Rating</small></p><div class='entry'>$message</div></div>";
$db = mysql_connect("host", "user", "password");
mysql_select_db("db", $db);
if (!$db)
{
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story', '$school','$location', '$sex', '$zipcode', '$name');";
$result = mysql_query($sql);
if($result)
{ $success = " Your hookup has been submitted ";}
else{
$error = "something went horribly wrong" . mysql_error();}
?>
I keep getting a syntax error when I submit this page, and if I comment $story out, the query runs fine. How can I fix this?
The most likely reason is that $story contains single quotes, which will break the query.
Protect it using mysql_real_escape_string
In general, this is a bad idea as it is open to SQL injection.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story',
'$school','$location', '$sex', '$zipcode', '$name');";
At least, use mysql_real_escape_string which will protect the input for characters that have special meaning in a MySQL query. Use it on all textual columns.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '" .
mysql_real_escape_string($story) . "','".
mysql_real_escape_string($school) . "','".
mysql_real_escape_string($location) . "', '$sex', '$zipcode', '" .
mysql_real_escape_string($name) ."');";
If you didn't care about SQL Injection ( though I dont know why would you wouldnt ) you could also use htmlspecialchars to fix your problem. mysql_real_escape_string is obviously the better choice though like #cyberkiwi said