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));
Related
I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}
I'm pretty new to PHP code.
I have a tabel that I want to insert in to but for some reason the insert statement does not work. The tabel has an ScanID column that AUTO_INCREMENT 's. I've tried a few things like just leaving the ScanID out of the statement but that didn't work either ( I also tried swapping the NULL with ' '). I was able to insert in to other tables where there isn't an ID that AUTO_INCREMENT's so my pretty sure that my connection works.
<?php
$xml=simplexml_load_file("someFile.xml");
$con =new PDO("mysql:host=localhost;dbname=testDB",'root','');
$ScanType="someType";
$start_date=$xml ->start_datetime;
$end_date=$xml ->finish_datetime;
$TargetTargetID="1";
$stmt=$con->prepare('insert into
Scan(ScanID, ScanType, start_date, end_date, TargetTargetID) values
(:ScanID, :ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanID',NULL);
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
$ScanID=$con->lastInsertId();
echo $ScanID;
?>
EDIT: this worked for me
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
No need to pass auto increment column value in insert query just remove from columns and values to
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
Remove from bind values
$stmt->bindValue('ScanID',NULL);
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.
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']."'
)");
I have a product info table with more than 130 columns/fields.
I want to write a php script that adds a new product to the table OR updates the existing product if it already exist. The first field is the product key.
The product information is stored in a numbered php array : $product_info[0] to $product_info[130].
Basically something like this :
INSERT INTO table (a,b,c) VALUES ($product_info[0],$product_info[1],$product_info[2])
ON DUPLICATE KEY UPDATE a='$product_info[0]', b='$product_info[1]', c='$product_info[2]'
Is there something more efficient than typing each of the 130 fields twice?
Yes, there is, use the VALUES() function:
INSERT INTO `table` (a, b, c) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE a = VALUES(a), b = VALUES (b), c = VALUES(c)
Basically, in the UPDATE part, VALUES(column) will return the specified value for that column for the current row in question. So you can do interesting things like:
ON DUPLICATE KEY UPDATE
a = VALUES(a),
b = VALUES(b) + VALUES(c),
The beauty of that syntax, is it also supports multiple insert rows:
INSERT INTO `table` (a, b, c)
VALUES (?, ?, ?),
VALUES (?, ?, ?),
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE a = VALUES(a), b = VALUES (b), c = VALUES(c)
Unfortunately MySQL does not support merging... having an ORM can help ease the pain of coding multiple IF EXISTS UPDATE ... ELSE INSERT code
REPLACE