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.
Related
I am new to all this MySQLi, and I can't seem to find any useful information that works for me.. I've tried the following code, but to no avail:
if(isset($_GET['submit']))
{
$stamp = date("D M d, Y G:i a");
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
}
I am unaware as to what I'm doing wrong, so maybe some insight? Or it would be great if someone could reference me to some websites? Hence nothing seems to work for me!
HTML is:
<form method="post">
<b>Submit a downtime report*</b>: <input type="submit" name="submit" value="Report">
</form>
You don't have to use date() function in PHP. You can use NOW() or CURRENT_TIMESTAMP() in MySQL
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES (NOW(), '" . USER_NAME . "')");
More date functions you can find here
I guess USER_NAME is a constant and it's set.
As for useful resources, have you tried the official documentation ?
http://php.net/manual/en/book.mysqli.php
It seems to be pretty comprehensive.
Change this to
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
to
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
Reason: timestamp is also a type in SQL hence you should use it like that.
"timestamp" is a MySQL keyword and so is interpreted as a data type rather than a column name and then the syntax doesn't make any sense. You can solve this by escaping the column name using back ticks. This is a good practice for all table and column names by the way, regardless of whether they are keywords or not. So changing the query as follows should work:
$mysqli->query("INSERT INTO `down` (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
I am inserting some data into a MySQL table using CodeIgniter. Because I am using INSERT IGNORE INTO and do not want to edit the active records class to enable this feature, I am generating the SQL query manually.
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $data['lat'] . "', '" . $data['lng'] . "', '" . $data['date'] . "', '" . $data['type'] . "')");
Problem: The query failed when the string in $data['type'] contained a single quote. How can I make it such that these characters that need to be escaped gets escaped automatically, like when using Active records?
Another way is to use Query Binding which automatically escapes all the values:
$sql = "INSERT IGNORE INTO my_table(lat, lng, date, type) VALUES (?,?,?,?);";
$this->db->query($sql, array($data['lat'], $data['lng'], $data['date'], $data['type']));
use $this->db->escape(); it will escape the string automatically
This function determines the data type so that it can escape only
string data. It also automatically adds single quotes around the data
so you don't have to:
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $this->db->escape($data['lat']) . "', '" . $this->db->escape($data['lng']) . "', '" . $this->db->escape($data['date']$this->db->escape . "', '" . $this->db->escape($data['type']) . "')");
Here is the reference Click Here
I am trying to insert a date from a variable into a mysql database. The format of the column is date and it has dates in the column. The dates in the column look like yyyy-mm-dd
my date variable also looks like this however it will not insert the date into the column and even i do not get an error just a white screen.
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
<?php
//this does work but it does not have the date.
mysql_query("INSERT INTO `invoices` (account_id, sales_rep, INV_ID)
VALUES ('".$acctid."', '".$row['8']."', '".$invid."')") or die("load1 -" . mysql_error());
not sure what the problem is. I have displayed the $date variable onto the screen and it looks fine ex. 2012-06-01
so I am not sure why it can not insert this into the database.
Your error is that you have a parse error in this line:
VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )")
Your server has display_errors turned off, so you're not seeing the fatal error output.
You can fix it by adding a concatenation operator (.) like so:
VALUES ('".$acctid."', '".$date."','".$row['8']."', '".$invid."' )")
Also, in the future, I find it more readable to write my queries like so:
VALUES ('{$acctid}', '{$date}', '{$row['8']}', '{$invid}')
If you prefer not to use interpolation (that's the method of string "injection" used above), you could still use concatenation (your original method) but use spaces to make it more readable (and easier to find syntax errors before you try to execute it):
"VALUES ('" . $acctid . "', '" . $date . "' , '" . $row['8'] . "', '" . $invid . "')";
And before all the haters shun me for suggesting interpolation over concatenation, let me refer you to this tweet by #rasmus stating that interpolation is actually faster than concatenation, these days.
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID) VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
?>
the error is:
PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING on line 1
There is no . after $date.
Try to use new \DateTime('yyyy-mm-dd')
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".new \DateTime('yyyy-mm-dd')."','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
You can use
mysql_query("INSERT INTO `vipanda2`.`invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".date('Y-m-d',mktime(0, 0, 0, date("m", $date), date("d", $date), date("Y", $date)))."','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
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
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) . "')";