php mysql insert statement using variables - php

my php code which is throwing errors is as follows:
$stmt = $con->prepare('INSERT INTO listOfRides (address, time) VALUES
('$address', '$time')') ;
I have looked at other posts and it seems I am using the variables correctly with the single quotes around them however the following error is being shown when visiting the URL:
Parse error: syntax error, unexpected T_VARIABLE in /home/gbidjght/public_html
/insertRide.php on line 79
Any help is appreciated

If you escaped the single quotes you would end up with the string literals "$address" and "$time" being inserted into your DB:
$stmt = $con->prepare('INSERT INTO listOfRides (address, time) VALUES (\'$address\', \'$time\')');
However assuming that they should be variables, you should use double quotes around your SQL statement to allow PHP to actually parse your variables as their values:
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES ('$address', '$time')");
That being said, since you're already preparing your statement, why not just use placeholders anyway? It'll be a safer way to protect against SQL injection.
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES (?, ?)");
$stmt->execute(array($address, $time));

change the outer quotes to double quotes
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES
('$address', '$time')") ;

You can't put mysql ' in php '
Use this
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES
('$address', '$time')") ;

Because of the 's the error is coming. Add " instead of '.Try this -
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES ('$address', '$time')") ;

$stmt = $con->prepare("INSERT INTO `listOfRides` (`address`, `time`)
VALUES
($address, $time)") ;

Related

How to use PHP prepare with zillions of fields of different types

I am inserting data that has VARCHAR, TIMESTAMP and DECIMAL kinds using prepare.
The data is already in the format needed by mySQL.
My problem is this. Suppose I had only 2 items to insert. I would do like this:
$stmt = $mysqli->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->bind_param("si", $_POST['name'], $_POST['age']);
My problem is the bind part. How do I do the bind when I have to insert 40 columns at once?
I can deal with the prepare part by doing this:
$sql = "INSERT INTO customers ($columns) VALUES ($values)";
$stmt = $mysqli->prepare($sql);
But the next line will result in a ridiculous long line, impossible to understand and very easy to go wrong.
$stmt->bind_param("ssssiidisisssiidiisssidiisidi", ....);
I don't see how I could build that in a loop for example.
How do I do that?
You can pass an array to the mysqli_stmt::bind_param() function as variable arguments with the ... syntax, introduced in PHP 5.6.
$params = ['name', 42];
$stmt = $mysqli->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->bind_param(str_repeat('s', count($params)), ...$params);
$stmt->execute();
You don't really need to set the data type individually for each column. You can treat them all as 's'.
I know you're asking about mysqli, but I'll just point out that this is easier with PDO:
$params = ['name', 42];
$stmt = $pdo->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->execute($params);

mysqli prepared statement with ADDTIME CURTIME fails

There are so many questions on SO for failed prepared statements, but I cannot find one which solves my exact problem (or explains it, atleast).
I'm trying to give my users a login-token which is valid for 5 minutes.
When I execute the query through PHPMyAdmin it works just fine:
WORKING QUERY
INSERT INTO LOGGEDIN (userID, loggedInToken, loggedInRefresh) VALUES
(1, "HJKFSJKFDSKLJFLS", ADDTIME(CURTIME(), '00:05:00'));
However, when trying to execute the query through PHP using a prepared statement it fails.
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
$stmt->bind_param("is", $userID, $token);
I get the 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 'VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))' at line 1
It is the exact same query so I think it's due to how the prepare handles the query.
I've also tried entering the '00:05:00' as a variable because I thought the ' was causing the error but it fails as well.
$five_minutes = '00:05:00';
$stmt->bind_param("iss", $userID, $token, $five_minutes);
When I remove the prepare and use the following query:
$query = "INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (" . $userID . ", '" . $token . "', ADDTIME(CURTIME(), '00:05:00'))";
if ($result = $mysqli->query($query)) {
...
It works fine but I would like to keep my code consistent and use a prepared statement everywhere I can.
How can I let this query execute properly using a prepared statement? If all else fails I think I could create the timestamp in PHP and pass it through to the database thus bypassing the whole ADDTIME calculation, but I would like to know what is causing the problem in the first place.
Problems need to be understood, not dodged.
You have a superfluous VALUES on your query:
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
^^
Remove that:
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");

prepared INSERT statement to get insert_id to use in a second prepared INSERT statement

Im trying to create my own register form but im having issues with prepared statements.
the idea is to create a prepared statement to insert info into the user table, then from that get the insert_id from the generated content to use in another insert statement
here is a version of my register script
<?php
$returnedId = '';
include "includes/dbconnect.php";
$stmt = $db->prepare("INSERT INTO `users`(`Username`, `Email`, `Password`) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $_POST['username'], $_POST['email'], $_POST['password']);
$stmt->execute();
$returnedId = $stmt->insert_id;
$stmt->close();
echo $returnedId;
$allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
$allergystmt->bind_param('ss', $returnedId, $_POST['check_list']);
$allergystmt->execute();
$allergystmt->close();
header('Location: index.php');
?>
the first prepared statement runs correctly and inserts information into the table, after that the $returnId variable is successfully echoed. next in the script is my second prepared statement, when it tries to run im getting the error that says:
Fatal error: Call to a member function bind_param() on a non-object in D:\filepath\register.php on line 17
it seems that my variable isnt being carried into the second prepared statement.
Your second query has syntax errors and failed to prepare. Since you have no error handling for database failures like this, your later code just blunders onwards:
$allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
^--- ^--^--- ^-- etc...
You cannot use ' quotes on table and field names. ' indicate strings. None of those field/table names are reserved words, so there is NO need to quote them at at all:
$allergystmt = $db->prepare("INSERT INTO user_allergy (user_id, allergy_id) VALUES (?, ?)");
if (!$allergystmt) { die($dbh->errorInfo()); }
Note the addition of the errorInfo() output. Never assume a DB operation was successful. Always assume failure, and treat success as a pleasant surprise.

inserting data from a form into your mysql database using php

i used this code
<?php
$conn = new PDO("mysql:host=localhost;dbname=CU4726629",'CU4726629','CU4726629');
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
header('Location: reviews.php');
?>
but it keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in
/home/4726629/public_html/check_login.php on line 5
Take this for an example:
<?php
// insert some data using a prepared statement
$stmt = $dbh->prepare("insert into test (name, value) values (:name, :value)");
// bind php variables to the named placeholders in the query
// they are both strings that will not be more than 64 chars long
$stmt->bindParam(':name', $name, PDO_PARAM_STR, 64);
$stmt->bindParam(':value', $value, PDO_PARAM_STR, 64);
// insert a record
$name = 'Foo';
$value = 'Bar';
$stmt->execute();
// and another
$name = 'Fu';
$value = 'Ba';
$stmt->execute();
// more if you like, but we're done
$stmt = null;
?>
You just wrote a string in your above code:
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
Above answers are correct, you will need to concat the strings to form a valid sql query. you can echo your $sql variable to check what is to be executed and if is valid sql query or not. you might want to look in to escaping variables you will be using in your sql queries else your app will be vulnerable to sql injections attacks.
look in to
http://php.net/manual/en/pdo.quote.php
http://www.php.net/manual/en/pdo.prepare.php
Also you will need to query you prepared sql statement.
look in to http://www.php.net/manual/en/pdo.query.php
A couple of errors:
1) you have to concat the strings!
like this:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
2) you are not using the PDO at all:
after you create the "insert" string you must query the db itself, something like using
$conn->query($sql);
nb: it is pseudocode
3) the main problem is that this approach is wrong.
constructing the queries in this way lead to many security problems.
Eg: what if I put "moviename" as "; drop table review;" ??? It will destroy your db.
So my advice is to use prepared statement:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$fill_array = array($_POST['username'], $_POST['moviename'], $_POST['ratings']);
$q->execute($fill_array);
You forgot dots:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
and fot the future for now your variables are not escaped so code is not secure
String in a SQL-Statment need ', only integer or float don't need this.
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ('".$_POST['username']."','".$_POST['moviename']."','".$_POST['ratings']."')";

If I use $_POST value directly in bindParam (mysqli) will there be a security issue?

I have been reading about using $_POST values being used directly in isert statements and understand that this is an invitation for trouble. What is not clear in any of the posts I read was -
Say my form is sending 7 items to my mysqli insertion script and I use the posted values like this:
$stmt = $mysqli->prepare("INSERT INTO `advertisements` (`from`, `r_u_res`, `email`, `blockname`, `floorno`, `doorno`, `content`) VALUES (?, ?, ?, ?, ?,?,?)");
$stmt->bind_param('sssssss', $_POST['from'], $_POST['rures'], $_POST['email'], $_POST['blockname'], $_POST['floorno'], $_POST['doorno'], $_POST['content']);
$stmt->execute();
$stmt->close();
Would that be the correct way to do it? Or should I first store the posted values in a new variable and use that variable while binding? - like this :
$postedfrom = $_POST['from'];
$postedrures = $_POST['rures'];
$postedemail = $_POST['email'];
$postedblockname = $_POST['blockname'];
$postedfloorno = $_POST['floorno'];
$posteddoorno = $_POST['doorno'];
$postedcontent = $_POST['content'];
$stmt = $mysqli->prepare("INSERT INTO `advertisements` (`from`, `r_u_res`, `email`, `blockname`, `floorno`, `doorno`, `content`) VALUES (?, ?, ?, ?, ?,?,?)");
$stmt->bind_param('sssssss', $postedfrom, $postedrures, $postedemail, $postedblockname, $postedfloorno, $posteddoorno, $postedcontent);
$stmt->execute();
$stmt->close();
I saw a post OO mysqli prepared statements help please where the answer does seem to be like the code above but I want to know whether doing it like the first code poses security issues...
both forms are equivalent from a security perspective as php first resolves the values to be passed in the method call to $stmt->bind_param, thus that function sees the exact same values in both cases.
ps: both snippets look ok to me.

Categories