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']."'
)");
Related
I am still learnig using php, and I got some problems.
So, I have a database named dbcoma and these tables;
pic of tables and the data
here is my question if I wanna make a registration for patient using php, what is the correct script?
I tried this one but it wasn't working (cant execute)
public function createPasien($id_alat, $id_patient, $passwordpas, $namepas, $age, $datein, $id_hospital, $id_alat){
$password = md5($passwordpas);
$stmt = $this->con->prepare("INSERT INTO `dbcoma`.`patient` (`id_patient`, `passwordpas`, `namepas`, `age`, `datein`, `id_alat`, `id_hospital`) VALUES (?, ?, ?, ?, ?, ?, ?);");
$stmt->bind_param("sssssss", $id_patient, $passwordpas, $namepas, $age, $datein, $id_alat, $id_hospital);
$stmt->execute();
// …
}
UPDATE: I FIXED IT AND FOUND THE PROBLEM. THANK YOU
There are some points to keep in mind:
Check the response return by execute() statement.
Echo the query and run it on the mysql terminal and see what happens.
While dealing with foreign key the value you are trying to insert must present in the master table, only then you can insert it in child table.
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.
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));
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)
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 1 year ago.
I have a function that generates a prepared INSERT statement based on an associative array of column names and values to be inserted into that column and a table name (a simple string):
function insert ($param, $table) {
$sqlString = "INSERT INTO $table (".implode(', ',array_keys($param)).') VALUES ('.str_repeat('?, ', (count($param) - 1)).'?)';
if ($statement = $this->conn->prepare($sqlString)):
$parameters = array_merge(array($this->bindParams($param), $param));
call_user_func_array(array($statement, 'bind_param', $parameters));
if (!$statement->execute()):
die('Error! '.$statement->error());
endif;
$statement->close();
return true;
else:
die("Could Not Run Statement");
endif;
}
My problem is that $this->conn->prepare (it's part of a class, conn is a NEW mysqli object, which works with no issues) returns false, but does not give me a reason why!
Here is a sample $sqlString that gets built for the prepare statement:
INSERT INTO students (PhoneNumber, FirstName, MiddleInit, LastName, Email, Password, SignupType, Active, SignupDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
Can anyone see a problem with this parameterized statement? Any reason the prepare function would return false?
I'm copying the solution into this answer so this can be given an upvote, otherwise the question will appear in the "unanswered questions" forever. I'm marking this answer CW so I won't get any points.
#Andrew E. says:
I just turned on
mysqli_report(MYSQLI_REPORT_ALL) to
get a better understanding of what was
going on - turns out that one of my
field names was incorrect - you'd
think that prepare() would throw an
exception, but it fails silently.
These are the main reasons I got this issue.
Error in the query
Trying to run two simultaneous queries (commands out of sync)
First you need to know the exact cause. for that, add following code.
if ($stmt === FALSE) {
die ("Error: " . $mysqli->error);
}
If you are running two simultaneous queries, store values from your first statement will resolve the issue.
$first_stmt->store_result()