What's the right way of using a MySQL function while using PHP PDO? The function NOW() gets saved as a string instead of showing the time.
$sth = $dbh->prepare("INSERT INTO pdo (namespace, count, teststring) VALUES (?, ?, ?)");
// these protect you from injection
$sth->bindParam(1, $_a);
$sth->bindParam(2, $_b);
$sth->bindParam(3, $_c);
$_a = 'Wishy-washy';
$_b = 123;
$_c = 'NOW()'; // Doesn't work. Comes out as the string 'NOW()' (w/o the quotes) and not as a date
I would not pass functions as the bound params:
$sth = $dbh->prepare("INSERT INTO pdo (namespace, count, teststring) VALUES (?, ?, NOW())");
$_a = 'Wishy-washy';
$_b = 123;
$sth->execute(array($_a, $_b));
Why not replace it to something like..
$_c = date("H:i:s");
Using the power of the PHP date function?
Related
I have tried whole day (again) but with error trying to insert in total of over billion of rows while inserting about 10k within one query. I want to use prepared statements to do this with MySQL, using innoDB tables. Hardware resources are not a problem, problem has all the time been indexing and one row / insert.
Do not say that I should use straight from list methods since I need to do some calculations before inserting. Input comes from file.
So I have a big while loop, looping text file lines and that's working fine.
I currently do it with inserting one per query.
$stmt = $conn->prepare("INSERT INTO $tableName(row1, row2, row3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $str1, $str2, $str3);
$stmt->execute();
I have looked at examples doing it like so:
$stmt = $conn->prepare("INSERT INTO $tableName(row1, row2, row3) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?) ..... ");
But I need to construct this to for like 5-10k rows for single query.
If someone has done something like this before, please give some reference to work with.
Thanks in advance!
The whole idea of a prepared query is that it reduces the overhead of setting up the query each time it's run – prepare once, execute repeatedly. That means there's not going to be a huge amount of difference (from the POV of the database) between running a prepared statement in a loop, or passing one giant query.
You don't include your whole code here, but an error that many people make is to include the statement preparation in the loop. Don't make that mistake! Something like this will be most efficient:
// these need a value before being used in bind_param
$str1 = $str2 = $str3 = "";
$stmt = $conn->prepare("INSERT INTO $tableName(row1, row2, row3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $str1, $str2, $str3);
while ($we_have_data) {
$str1 = "foo";
$str2 = "bar";
$str3 = "baz";
$stmt->execute();
}
Though I always recommend using PDO prepared statements, as you get to avoid the potential mess of binding parameters:
// assuming $conn is a PDO object now
$stmt = $conn->prepare("INSERT INTO $tableName(row1, row2, row3) VALUES (?, ?, ?)");
while ($we_have_data) {
$str1 = "foo";
$str2 = "bar";
$str3 = "baz";
$stmt->execute([$str1, $str2, $str3]);
}
Maybe because limit executing time from server. Try to use insert batch.
Add to array
$i = 0;
.. looping
$i++;
$mark[] = '(?,?,?)';
$val[] = $str1.",".$str2.",".$str3;
// check when 1k record
if($i == 1000){
$stmt = $conn->prepare("INSERT INTO ? (row1, row2, row3) VALUES ".implode(',', $mark);
$stmt->bind_param("sss", implode(',', $val));
$stmt->execute();
$mark = []; $val = []; $i = 0; // reset
}
I have a table and theDate field is structured as INT (32) .
Writing PHP scripts I would like to use mySQL PDO to insert the unix timestamp as an integer into theDate INT table field. What is the best way to do this? And what is the most efficient size for my theDate field? 8, 16, 32?
code:
$theDate = now(); // this returns a 0 in theDate mySQL field
$stmt = $db->prepare("INSERT INTO countries(name, capital, language, theDate) VALUES (:country, :capital, :language, :theDate)");
$stmt->bindParam(':country', $country, PDO::PARAM_STR, 100);
$stmt->bindParam(':capital', $capital, PDO::PARAM_STR, 100);
$stmt->bindParam(':language', $language, PDO::PARAM_STR, 100);
$stmt->bindParam(':theDate', $theDate );
if($stmt->execute()) {
echo '1 row has been inserted';
}
I have googled this and searched this site.. can't find a good answer
thanks
The best way to store a datetime information in mysql is to use a datetime field. For which you can use the very now() function you were trying. But of course you have to call it in SQL, not PHP:
$sql = "INSERT INTO countries(name, capital, language, theDate) VALUES (?, ?, ?, now())";
$stmt = $db->prepare($sql);
$stmt->execute([$country,$capital,$language]);
if you insist on using unreliable and outdated unix_timestamp, you have to use unix_timestamp() SQL function instead of now(). The code would be the same as above, save for the function name.
If you want to send an int value to a database via PDO - just send it:
$theDate = time();
$sql = "INSERT INTO countries(name, capital, language, theDate) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute([$country,$capital,$language,$theDate]);
When I send below query to the database from a php page, the passed values are not displaying. But each time a newrow is added.
$query1="INSERT INTO login(username,password,type)
VALUES("."'".$m_nic."',"."'".$f_name."',"."'".$type."')";
$login_set=mysql_query($query1,$connection);
How can I prevent SQL injection in PHP?
mysql_* functions are deprecated. USe mysqli_*
Your code should look like this:
$q = mysqli_prepare($connection, 'INSERT INTO login (username, password, type) VALUES (?, ?, ?)';
mysqli_stmt_bind_param($q, 'sss', $m_nic, $f_name, $type);
mysqli_stmt_execute($q);
I'm trying to insert data from a form into a database using PHP and Mysqli but I can't get it working! My database has 4 fields: DATE, TITLE, CONTENT, ID. The ID field is auto-increment.
I've checked the connection and that's working fine. I've also echoed the form field values and the $blogDate variable I created, they're all fine too.
Here's my prepared statement:
if ($newBlog = $mysqli->prepare('INSERT INTO Blog VALUES ($blogDate, $_POST["bTitle"], $_POST["bContent"])')) {
$newBlog->execute();
$newBlog->close();
}
It's just not inserting the values into my table.
You are generating SQL containing strings that are not quoted or escaped.
Don't insert the data directly into the SQL string, use placeholders (?) and then bind the parameters before executing.
$query = "INSERT INTO Blog VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
Since you are aware about prepared statement:
$newBlog = $mysqli->prepare('INSERT INTO Blog (`dateCol`, `titleCol`, `contentCol`) VALUES (?, ?, ?)');
$newBlog->bind_param( 'sss', $blogDate, $_POST["bTitle"], $_POST["bContent"] );
$newBlog->execute();
$newBlog->close();
since you are using auto increment field you need to specify column name and then values
try this code
$query = "INSERT INTO Blog (colname_1,colname_2,colname_3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
I was wondering if someone could help me.
Im trying to integrate some code into my application, the code that i need to integrate is written with PDO statements and i have no idea how it goes.
I was wondering if someone could help me convert it.
The code is as follows
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
$stmt = $PDO->prepare($sql);
$stmt->execute($args);
if (empty($mid)) {
$mid = $PDO->lastInsertId();
}
$insertSql = "insert into message2_recips values ";
$holders = array();
$params = array();
foreach ($rows as $row) {
$holders[] = "(?, ?, ?, ?)";
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
$insertSql .= implode(',', $holders);
$stmt = $PDO->prepare($insertSql);
$stmt->execute($params);
You shoudl use PDO unles for some technical reason you cant. If you dont know it, learn it. Maybe this will get you started:
/*
This the actual SQL query the "?" will be replaced with the values, and escaped accordingly
- ie. you dont need to use the equiv of mysql_real_escape_string - its going to do it
autmatically
*/
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
// these are the values that will replace the ?
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
// create a prepared statement object
$stmt = $PDO->prepare($sql);
// execute the statement with $args passed in to be used in place of the ?
// so the final query looks something like:
// insert into message2 (mid, seq, created_on_ip, created_by, body) values ($mid, $seq, 1.2.2.1, $currentUser, $body)
$stmt->execute($args);
if (empty($mid)) {
// $mid id is the value of the primary key for the last insert
$mid = $PDO->lastInsertId();
}
// create the first part of another query
$insertSql = "insert into message2_recips values ";
// an array for placeholders - ie. ? in the unprepared sql string
$holders = array();
// array for the params we will pass in as values to be substituted for the ?
$params = array();
// im not sure what the $rows are, but it looks like what we will do is loop
// over a recordset of related rows and do additional inserts based upon them
foreach ($rows as $row) {
// add a place holder string for this row
$holders[] = "(?, ?, ?, ?)";
// assign params
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
// modify the query string to have additional place holders
// so if we have 3 rows the query will look like this:
// insert into message2_recips values (?, ?, ?, ?),(?, ?, ?, ?),(?, ?, ?, ?)
$insertSql .= implode(',', $holders);
// create a prepared statment
$stmt = $PDO->prepare($insertSql);
// execute the statement with the params
$stmt->execute($params);
PDO really is better. It has the same functionality as MySQLi but with a consistent interface across DB drivers (ie. as long as your SQL is compliant with a different database you can theoretically use the exact same php code with mysql, sqlite, postresql, etc.) AND much better parameter binding for prepared statements. Since you shouldnt be using the mysql extension any way, and MySQLi is more cumbersome to work with than PDO its really a no-brainer unless you specifically have to support an older version of PHP.