i'm trying to INSERT a sql query but it does not work - I got no errors, $pdo->errorInfo(); only returns Array and in the mysql is nothing to see!
Im 100% sure that $text, $file and $title is set (i've check that with echo) In every other php file this pdo connection works with include but not in the dev.php what should i do???
datenbank.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'password');
?>
dev.php
include("datenbank.php");
// Prepare an insert statement
$post = $pdo->prepare("INSERT INTO news (text, date, file, title) VALUES ($text, NOW(), $file, $title)");
$post->execute();
$help = $pdo->errorInfo();
You don't use the parameters markers in your prepare PDO stament. When you prepare a query using PDO extension, you need put markers in your query statement and indicate the value of those markers in the execute function like an associative array.
You can use markers like :marker or question marks ? and your query would be like that:
include("datenbank.php");
// Prepare an insert statement with marks params
$post = $pdo->prepare(INSERT INTO news (text, date, file, title) VALUES (:text, NOW(), :file, :title));
//execute statements with the marks values in prapare function params
$post->execute(array(':text' => $text, ':file' => $file, ':title' => $title));
Edit: PD: This prevents the SQL inyection.......
for string value you need quote
$post = $pdo->prepare("INSERT INTO news (text, date, file, title)
VALUES ('$text', NOW(),'$file', '$title')");
anyway you should not use php var in sql , you are at risk for sqlinjection .. use prepared statements and binding param instead
$stmt = $conn->prepare("INSERT INTO news (text, date, file, title)
VALUES (:text, NOW(), :file, :title)");
$stmt->bindParam(':text', $text);
$stmt->bindParam(':file', $file);
$stmt->bindParam(':title', $title);
$stmt->execute();
Related
I'm looking for a SQL-injection-secure technique to insert a lot of rows (ca. 2000) at once with PHP and MySQLi.
I have an array with all the values that have to be include.
Currently I'm doing that:
<?php
$array = array("array", "with", "about", "2000", "values");
foreach ($array as $one)
{
$query = "INSERT INTO table (link) VALUES ( ?)";
$stmt = $mysqli->prepare($query);
$stmt ->bind_param("s", $one);
$stmt->execute();
$stmt->close();
}
?>
I tried call_user_func_array(), but it caused a stack overflow.
What is a faster method to do this (like inserting them all at once?), but still secure against SQL injections (like a prepared statement) and stack overflows?
You should be able to greatly increase the speed by putting your inserts inside a transaction. You can also move your prepare and bind statements outside of your loop.
$array = array("array", "with", "about", "2000", "values");
$query = "INSERT INTO table (link) VALUES (?)";
$stmt = $mysqli->prepare($query);
$stmt ->bind_param("s", $one);
$mysqli->query("START TRANSACTION");
foreach ($array as $one) {
$stmt->execute();
}
$stmt->close();
$mysqli->query("COMMIT");
I tested this code with 10,000 iterations on my web server.
Without transaction: 226 seconds.
With transaction: 2 seconds.
Or a two order of magnitude speed increase, at least for that test.
Trying this again, I don't see why your original code won't work with minor modifications:
$query = "INSERT INTO table (link) VALUES (?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $one);
foreach ($array as $one) {
$stmt->execute();
}
$stmt->close();
Yes, you can build a single big query manually, with something like:
$query = "";
foreach ($array as $curvalue) {
if ($query)
$query .= ",";
$query .= "('" . $mysqli->real_escape_string($curvalue) . "')";
}
if ($query) {
$query = "INSERT INTO table (link) VALUES " . $query;
$mysqli->query($query);
}
You should first convert your array into a string. Given that it is an array of strings (not a two-dimentional array), you can use the implode function.
Please be aware that each value should be enclosed into parenthesis and properly escaped to ensure a correct INSERT statement and to avoid the risk of an SQL injection. For proper escaping you can use the quote method of the PDOConnection -- assuming you're connecting to MySQL through PDO. To perform this operation on every entry of your array, you can use array_map.
After escaping each value and imploding them into a single string, you need to put them into the INSERT statement. This can be done with sprintf.
Example:
<?php
$connection = new PDO(/*...*/);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dataToBeSaved = [
'some',
'data',
'with "quotes"',
'and statements\'); DROP DATABASE facebook_main; --'
];
$connection->query(
sprintf(
'INSERT INTO table (link) VALUES %s',
implode(',',
// for each entry of the array
array_map(function($entry) use ($connection) {
// escape it and wrap it in parenthesis
return sprintf('(%s)', $connection->quote($entry));
}, $dataToBeSaved)
)
)
);
Note: depending on the amount of records you're willing to insert into the database, you may want to split them into several INSERT statements.
I am trying to get the id of the last record inserted in an mssql database using pdo via php. I HAVE read many posts, but still can't get this simple example to work, so I am turning to you. Many of the previous answers only give the SQL code, but don't explain how to incorporate that into the PHP. I honestly don't think this is a duplicate. The basic insert code is:
$CustID = "a123";
$Name="James"
$stmt = "
INSERT INTO OrderHeader (
CustID,
Name
) VALUES (
:CustID,
:Name
)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
I have to use PDO querying an MSSQL database. Unfortunately, the driver does not support the lastinsertid() function with this database. I've read some solutions, but need more help in getting them to work.
One post here suggests using SELECT SCOPE_IDENTITY(), but does not give an example of how incorporate this into the basic insert code above. Another user suggested:
$temp = $stmt->fetch(PDO::FETCH_ASSOC);
But, that didn't yield any result.
If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:
$CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query
Read more at:
https://msdn.microsoft.com/en-us/library/ms177564.aspx
http://php.net/manual/es/pdo.lastinsertid.php
I have crateio set up and it's working fine using the PDO class.
I'm, trying to get a set of geopoints into the db using binds.
I have tried foreach but doesn't seem to work, I've tried this - which also doesn't work.
The geopoint column is set to geo_point_array.
$route="[[30.33333, -6.13336],[30.33333, -6.13336]]";
$db = new Database;
$db->Query("insert into geopoints (id, longlat, name) values ('33',?,'pat')");
$db->bind(1, $route);
$db->execute();
How do I add this set of cordinates to the db?
Thanks
GeoPoint is not supported as a native type in Crate's PDO driver yet, however you can use an double ARRAY.
From the Crate documentation:
Columns with the geo_point are represented and inserted using a double
array in the following format: [lon_value, lat_value]
I also strongly recommend to do parameter substitution for the other values.
use Crate\PDO\PDO;
$route = [[30.33333, -6.13336], [30.33333, -6.13336]];
$db = new PDO('crate:...');
$stmt = $db->query("insert into geopoints (id, longlat, name) values (?, ?, ?)");
$stmt->bind(1, 33, PDO::PARAM_INT);
$stmt->bind(2, $route, PDO::PARAM_ARRAY);
$stmt->bind(3, 'pat', PDO::PARAM_STR);
$stmt->execute();
PDO::query returns PDOStatement:
$route="[[30.33333, -6.13336],[30.33333, -6.13336]]";
//If Dateabase is a sublcass of PDO
//$db = new Database;
$db = new PDO(...);
$stmt = $db->query("insert into geopoints (id, longlat, name) values ('33',?,'pat')");
$stmt->bind(1, $route, PDO::PARAM_STR);
$stmt->execute();
I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.
Following is the code :
$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);
$arr = array("col"=>"aes_encrypt ($val, $DBKey)");
I know i am doing it wrong, but not able to find correct way.
You are almost there, here is a simplified version:
<?php
$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);
// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username'] gets assigned to first ? mark
// $fill_array[1] = $_POST['password'] gets assigned to second ? mark
// $fill_array[2] = $DBKey gets assigned to third ? mark
$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks
// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE
// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error
// How many inserted?
echo $stmt->rowCount();
?>
you can try it like this.
$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));
I'm trying to allow a user to comment on a profile on my website. I have the following php -- updated:
<?php
// Insert Comments into Database that user provides
$comm = mysql_real_escape_string($_POST['addComment']);
$pID4 = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT);
$cID = mysql_real_escape_string($_POST['courseInfoDD']);
$username = "###";
$password = "####";
$pdo4 = new PDO('mysql:host=localhost;dbname=###', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES(:info, :pID, :cID)
');
$sth3->execute(array(
':info' => $comm, ':pID' => $pID3, ':cID' => $cID
));
?>
DB Table "Comment"
http://postimage.org/image/16sbr0jd0/ (Moderator please convert this to show image, please)
HTML:
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
Error Given:
No pID specified . When I try to insert a comment.
You are using single-quotes in your insert statement :
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES($comm, $pID3, $cID)
');
With those simple quotes, $comm will not be evaluated -- and the literal $comm string will be sent to the database -- resulting in something you probably don't quite expect.
If you want variables to be interpolated, you should use double-quotes around your string.
But, as you are trying to use prepared statements, that's not what you should do, actually.
Instead, you should use placeholders in the statement -- and, then, bind those to your data, when executing the statement.
Your prepare would look a bit like this, I suppose :
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES(:comm, :pID3, :cID)
');
Note the :comm, :pID3, and :cID placeholders.
And, then, when executing the statement, you'll actually pass some real data, to correspond to the placeholders :
$sth3->execute(array(
':comm' => $comm,
':pID3' => $pID3,
':cID' => $cID,
));
Additional note : as you are using prepared statements, you don't have to use mysql_real_escape_string() (which is not a PDO-related function, BTW, and should only be used when working with mysql_* functions) : the escaping is dealt by the prepared statement mecanism itself.
The parameters to the PDO prepared statement should be used like this:
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES(:info, :pID, :cID)
');
$sth3->execute(array(
':info' => $comm, ':pID' => $pID3, ':cID' => $cID
));
First set up the "slots" for the values, then supply them when you run the query.
$variables in single quote strings are not being processed. Use double quotes instead and add quotes for the SQL statement itself:
$sth3 = $pdo3->prepare("
INSERT INTO Comment (info, pID, cID)
VALUES('$comm', '$pID3', '$cID')
");
our problem has nothing to do not with mysql not with comments.
It's basic PHP strings syntax.
Use double quotes if you want variables to be interpreted in a string.
However, you shouldn't add variables into query directly, but rather bins them