I need to convert an existing project from mysql to mysqli and using prepared statement.
In the existing project there are queries that uses repeated variable values.
One such example is this: where the $prev_yr is used 3 times.
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '$prev_cl', '$prev_yr', '$prev_lvl', '', '123456789', '$prev_yr-01-01', '$prev_yr-12-31' from student Where StudentID in ($ids) ";
Is there a better method than this:
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '?', '?', '?', '', '123456789', '?-01-01', '?-12-31' from student Where StudentID in (?) ";
$stmt = $mysqli->prepare($sqlins);
$stmt->bind_param("ssssss", $prev_cl,$prev_yr,$prev_lvl,$prev_yr,$prev_yr,$ids);
$stmt->execute();
I am wondering if there is a way of binding the $prev_yr once for all 3 occurrences.
Because there are other queries that may have 2 occurrences of $prev_lvl, 5 occurrences of $prev_yr etc in one statement. The idea is that when the repeated occurrences of multiple variables becomes many in a statement - it becomes quite confusing to arrange them in the bind_param.
Any solution?
Thank you.
Does it even work like that, typical you wont't do this '?-01-01' in a query. I haven't used Mysqli, in about 4 years, as all I use now a days is PDO. But as far as I know when you send that to prepare it's gonna puke on the ? being in a string.
I would split it, there actually is no real need to do the select because the only thing being selected is the studentID which you already have. Simply
$insert = $mysqli->prepare("Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
foreach( $ids AS $id ){
$stmt->bind_param("issssiss", $id, $prev_cl,$prev_yr,$prev_lvl,'', '123456789', $prev_yr.'-01-01',$prev_yr.'-12-31');
$stmt->execute();
}
I can't test it so hopefully I got everything in the right place.
As I said I don't think you can bind to the Fields part of the query and certainly not inside a partial string, besides it's making a select that is un-needed. Just make sure to prepare the insert before the loop.
Just to clearly the only thing that select actually gets from the DB is this
select StudentID ... from student Where StudentID in (?)
The rest are added in as "fake" columns, I don't know the term for it. It's difficult to read the original query..
I am wondering if there is a way of binding the $prev_yr once for all 3 occurrences.
No.
Besides, it wouldn't work this way anyway, as you cannot bind just an arbitrary query part of your choice. You can bind a complete data literal only. Means instead of '?-01-01' it should be just ?, whereas in your PHP code you should make it
$dateStart = "$prev_yr-01-01";
and then bind this variable for the whole value. So there will be no more repeating variables.
Related
I am trying to insert a record to a table with 2 column but I get this error.
My error starts in part of the execute. Anyone that can help me out with this ?
I am using PDO.
My code:
global $conn_kl;
$sql = $conn_kl->prepare("INSERT INTO order_producten VALUES (?,?)");
$sql->execute(array($product_id, $bewerking_id));
The issue is here:
INSERT INTO order_producten VALUES (?,?)
here columns are not defined in this query, in this case it is expected that you have to pass the values for all columns in the table. But you want to insert the values for only 2 columns, so please please specify that columns names like:
INSERT INTO order_producten(column_name1, column_name2) VALUES (?,?)
order_producten will have more or less than two columns and you are setting only two values.
Please specify columns after table name. for example,
INSERT INTO order_producten(id, name) VALUES(?, ?)
For example, code something like this were working for me:
global $conn_kl;
$sql = $conn_kl->prepare("INSERT INTO `order_bewerkingen` VALUES (null, ?, ?, ?)");
$sql->execute(array($order_id, $method, $position));
Using prepared statements, I've got 23 values that are going to be entered (see below). Does this mean I need to type out 23 ? placements or is there some kind of default / shorthand?
INSERT INTO table
(
job_id, property_title, property_location, property_price, number_of_bedrooms,
number_of_receptions, number_of_bathrooms, epc, train_station_miles,
garden_acres, garage, off_road_parking, main_photo,
photo_1, photo_2, return_email, office,
additional_information, timestamp_added, added_by_user_id, timestamp_updated,
updated_by_user_id, status_id
)
VALUES (?, ?, ?, ?,......etc x 23)
I've never thought about this before as I've only used a smaller number of values but 23 seems a bit excessive if there is some kind of shorthand
This should be suitable for you, to shorthand binding all of your inputs into the query I'd recommend this code:
$placeholders = implode(', ', array_fill(0, 23, '?'));
$stmt = $connection->prepare("INSERT INTO table
(
... rest of the statement....
)
VALUES ($placeholders)");
I am new to MySQL and hope someone can help me with this.
I currently use the following as part of a longer statement in PHP in order to write something to a db table which works as intended:
$stmt = $conn->prepare("INSERT INTO History (email, year, halfYear, language, content) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("siiss", $email, $year, $halfYear, $language, $content);
$stmt->execute();
$result = $stmt->get_result();
How can I check if the corresponding email address ($email) already has 3 entries in the db and only write in the db when it has 2 or less entries (otherwise I just want to echo something) ?
I was thinking I could use something like $result->num_rows but wasn't sure how to apply this here.
Can someone help me with this ?
Many thanks in advance,
Mike
As per requested by the OP.
You first need to count the results in a SELECT all set inside a conditional statement.
If the query matches the criteria, perform the next one.
Example using num_rows:
if($result->num_rows == 3){
// do something
}
else {
// do something else
}
or num_rows >= 3 should you want to check if equal and/or more than 3 also.
Reference:
http://php.net/manual/en/mysqli-result.num-rows.php
Sidenote:
Be careful with your use of year it is a MySQL reserved keyword:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
You can still use it, but just as long as you wrap it in ticks.
I.e.:
(email, `year`, halfYear, language, content)
For example i send the following id:
$user->id = '1{3}4{5}6';
Represents:
$user->id(=1{3}4{5}6){$option(=3)}$value(=4){$option(=5)}$value(=6)
I now need to insert to database using prepared statements for each $option and $value pair.
the sql looks as following:
if ($user->attr == 1) {
$sth = $this->dbh->prepare("insert into customers_basket_attributes
(customers_id,
products_id,
products_options_id,
products_options_value_id)
values ('1', ?, ?, ?)");
$sth->execute(array($user->id, $option, $value));
return json_encode(1);
}
I want to avoid falling back to jQuery for each db insertion.
as far as I understand, this $user->id = '1{3}4{5}6'; decomposes:
Product_id = 1
Option_3 = 4
Option_5 = 6
and you want to store that in to records like:
products_id products_options_id products_options_value_id
1 3 4
1 5 6
From my point of view, you basically need as much inserts as you have rows above. You may combine that in to one insert with multiple rows:
insert into customers_basket_attributes
(customers_id,
products_id,
products_options_id,
products_options_value_id)
values (nn, 1,3,4),(nn, 1,5,6)
putting this into a prepared statement is somehow fiddling around with arrays, but should be achievable. Probably its clearer to just issue one insert per row, the cost is marginal anyway.
Here's the line of my code that is supposed to insert the row:
$query=mysqli_query($con,"insert * into orders
values
( ".$user_index.",".$order_date.",
".$_POST['item_number'].",".$_POST['price'].",
".$_POST['tax'].",'".$_POST['pay_method']."')
");
My connection doesn't throw any errors ever either. Also, the line of code after it definitely executes. This is my first time using the date data type with PHP and MySQL, but I'm inserting the date in the format yyyymmdd. I'm so frustrated. I checked everywhere online. Can you please help me?
The main problem with your query is the *. That is invalid for an INSERT statement.
Secondly, to avoid SQL injection vulnerabilities, you should be using a prepared statement with bound parameters. You should probably also use some form of error checking. For example
$stmt = $con->prepare('INSERT INTO `orders` VALUES (?, ?, ?, ?, ?, ?)');
if ($stmt === false) {
throw new Exception($con->error);
}
$stmt->bind_param('ssssss', $user_index, $order_date, $_POST['item_number'],
$_POST['price'], $_POST['tax'], $_POST['pay_method']);
if (!$stmt->execute()) {
throw new Exception($stmt->error);
}
FYI, without knowing the data types for your columns, I've assumed they're all strings.
First you have to remove * from the insert query
Second if you are inserting values like this make sure no of column in table is same as no of values you are inserting here(In this case 6)
There is so much wrong with your query. look at the documentation for proper syntax
mysqli_query($con,"INSERT INTO table_name (field1,field2,field1) values ('value1','value2','value3')");
In Specific to your problem
$query=mysqli_query($con,"INSERT INTO orders (your fields Here ) VALUES (
'".$user_index."', '".$order_date."', '".$_POST['item_number']."',
'".$_POST['price']."', '".$_POST['tax']."', '".$_POST['pay_method']."'
)");