The tablename will get compared against a whitelist of acceptable tables before hand by checking a table that list those tables. That list has to be dynamic which is why I opted out of using an array. Are the variables in the set variables section secure? They are coming user submitted post data.
if ($stmt = $mysqli->prepare("INSERT INTO `" . mysql_real_escape_string($tablename) . "` (item_name, item_price, item_position, item_type, multi_link_id) values (?, ?, ?, ?, ?)")) {
//Build Parameters
$stmt->bind_param('sdiii', $additemnameb, $additempriceb, $itempositionb, $itemtypeb, $linkidb);
//Set Variables
$additemnameb = $additemname;
$additempriceb = $additemprice;
$itempositionb = $itemposition;
$itemtypeb = $itemtype;
$linkidb = $linkid;
//Execute Statement
$stmt->execute();
//Close Statement
$stmt->close();
}else{
//Errors
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
Edited to have an actual question to be clear what I'm concerned about.
To answer your questions YES the variables in the // Set Variables section are secure, or more technically the variables will become secure before the query is executed. Mysqli takes care of it for you.
Related
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.
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']."')";
Here is prepare update statement and I think I Have the Variable types out of whack, not sure.
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE `Calibration_and_Inspection_Register` SET `item_type` = ?, `location` = ?, `date_last_test` = ?, `serial_number` = ?, `date_next_test` = ?, `comments` = ?
WHERE `id`=?"))
{
$stmt->bind_param("issdsds",`$id`, `$item_type`, `$location`, `$date_last_test`, `$serial_number`, `$date_next_test`, `$comments`);
$stmt->execute();
$stmt->close();
}
Order is important if you are not using named parameters. Since id is last parameter in the statement, it needs to be the last in the list of bound parameters as well.
Back-ticks around your parameter variables names in bind_param() call are also probably giving you errors. It should look like this:
$stmt->bind_param("ssdsdsi",$item_type, $location, $date_last_test, $serial_number, $date_next_test, $comments, $id);
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.
So this is my current code:
function addPage($uniquename, $ordernum, $title, $author, $content, $privilege, $description=NULL, $keywords=NULL){
if (!$description) $description = NULL;
if (!$keywords) $keywords = NULL;
//UPDATE `table` SET `ordernum` = `ordernum` + 1 WHERE `ordernum` >= 2
$query = "UPDATE ".$this->prefix."page SET ordernum = ordernum+1 WHERE ordernum >= ?";
if ($stmt = $this->db->prepare($query)){
$stmt->bind_param("i", $ordernum);
$stmt->execute();
if (!arCheck($stmt)) return false;
} else {
$this->stmtError("addPage", $stmt->error);
}
$query = "INSERT INTO ".$this->prefix."page VALUES (LCASE(?), ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = $this->db->prepare($query)){
$stmt->bind_param("sisisssi", $uniquename, $ordernum, $title, $author, $content, $description, $keywords, $privilege);
$stmt->execute();
return arCheck($stmt);
} else {
$this->stmtError("addPage", $stmt->error);
}
}
It is suppose to add a new page to the datatable. The MySQL is courtesy of Phil Hunt from Store the order of something in MySQL
I know that you can use multiquery to accomplish the same thing, however I was told that prepared statement is better in performance, and security. Is there another way to do this? Like a prepared multi query?
Also, what about doing Transactions? I'm not fully sure of what that is, I assume that it's if, let's say, the INSERT statement fails, it will undo the UPDATE statement as well?
NOTE: the arCheck function will close the statement.
Prepared statements are indeed faster for repeated queries, at least in most cases. They're also safer because they automatically escape input values, preventing SQL injection attacks. If you want to use them in PHP you'll need the MySQLi extension.
You appear to have the right idea about transactions. With MySQLi there are commit and rollback methods, otherwise you can use mysql_query("COMMIT") or mysql_query("ROLLBACK").