I have problem my code not working
I need to write 5 columns
can you explain how to can I use this code right
$val="('".implode("'), ('",$student)."')";
$sql = "INSERT INTO `tbl_student`
(`student_name`) VALUES ".$val.";";
I think this is what you're trying to do:
$val = "('".implode("','", $student)."')";
$keys = "(".implode(",", array_keys($student)).")";
$sql = "INSERT INTO tbl_student ".$keys." VALUES ".$val.";";
Warning: you should make sure your code is not subject to mysql injection. Values coming from the $student array should be sanitized if they comes from user input.
Related
i have a sql query to insert data without col names :
$sql = "INSERT INTO test_table VALUES (null,1,2,3) ";
if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}
I want to insert 1,2,3 as array , something like this:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,$data) ";
if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}
I tried php implode function too, but it didn't worked. Any help will be appreciated. Thank you!
You didn't provide the table structure that it is going into, but if all you are wanting to solve for is having the $data array split into constituent parts you could do it several ways:
a) implode(), although you already mentioned trying it, should work just fine:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,".implode(',',$data).")";
b) reference each array index:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,{$data[0]},{$data[1]},{$data[2]})";
That only works if you have a set amount of values in the array however.
c) loop over the array:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null"
foreach($data as $value){ $sql .= ",$value"; }
$sql .= ")";
Hope that helps, if not please provide more details about the structure of both the data going in and the database table so we can better understand the issue.
I've tried to follow several answers on this question but can't seem to get it to work for my specific problem.
I want to insert data but only if the flight_number doesn't exists already. How can I do that?
$sql = mysqli_query($con,
"INSERT INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Rob since you saying flight_number is a unique then you can use INSERT IGNORE
<?php
$sql = "INSERT IGNORE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('isss',$flight_number,$mission_name,$core_serial,$payload_id);
if($stmt->execute()){
echo 'data inserted';
// INSERT YOUR DATA
}else{
echo $con->error;
}
?>
OR you could select any row from your database that equal to the provided flight number then if u getting results don't insert.
$sql = "SELECT mission_name WHERE flight_number = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$flight_number);
if(mysqli_num_rows($stmt) === 0){
// INSERT YOUR DATA
}
A unique index on flight number should do the trick.
CREATE UNIQUE INDEX flight_number_index
ON space (flight_number);
If you want to replace the existing row with the new one use the following:
$sql = mysqli_query($con,
"REPLACE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Make note that I just copied your code and changed INSERT to REPLACE to make it easy to understand. PLEASE PLEASE PLEASE do not use this code in production because it is vulnerable to injection.
If you don't want to replace the existing row, run an insert and check for errors. If there is an error related to the index, the row already exists.
Disclaimer: I haven't tested any of this code, so there may be typos.
My laravel 4 query is like below:
foreach (Input::get('classrooms') as $keyc=>$valuec) {
foreach (Input::get('subject') as $keys=>$values) {
$valuesArray[] = "('".$valuec."','".$values."')";
}
}
$someVariable = implode(",",$valuesArray);
DB::select( DB::raw("INSERT IGNORE INTO classrooms_subjects (`classroom_id`,`subject_id`) VALUES $someVariable"));
I am really concerned if thats the safest way and any solution for this..
I have done some research and found a way but not sure if its safe:
please let me know if below code is safe:
$sql = "INSERT INTO classrooms_subjects (".implode(",", $columns).") ";
$sql .= " SELECT ".implode(",", $columns)." FROM classrooms_subjects WHERE id IN (".$toCopy.")";
DB::insert($sql);
If you need to bind some data then try like this (according to the docs):
DB::insert(
'INSERT IGNORE INTO classrooms_subjects (`classroom_id`,`subject_id`) VALUES (?, ?)',
[$classroomId, $subjectId]
);
You can pass data with array as a secound parameter here.
I am really new at php/mysql, so I hope you will bear with me!
This code is part of a larger script, but I think it is the crucial parts needed to help me further.
$order_id = $_POST['order_ids'];
$order_ids = implode(",",$order_id);
<input type="text" name="order_ids[]" value="123">
<input type="text" name="order_ids[]" value="456">
$query = "INSERT INTO order_list (id,order_id) VALUES (LAST_INSERT_ID(),'$order_ids')";
I would like to get:
id|order_id
10|123
10|456
Instead of what I get now
id|order_id
10|123, 456
UPDATE
The code from #Ido seems to work out of the box, I have one more field input I would like to add as well to the column which in the table is called "amount" which is similar to the order_id field input.
$order_amount = $_POST['order_amounts_field'];
$order_amounts = implode(",",$order_amount);
I tried copying this and changing with the other one, but soon realized I have to execute both inputs in the same query so as to get them in the same row:
$order_ids = array();
foreach($order_id as $id)
$order_ids[] = "(LAST_INSERT_ID(), '". $id ."')";
$order_ids = implode(", ", $order_ids);
$query = "INSERT INTO order_list (id,order_id) VALUES $order_ids";
$order_ids = array();
foreach($order_id as $id)
$order_ids[] = "(LAST_INSERT_ID(), '". $id ."')";
$order_ids = implode(", ", $order_ids);
$query = "INSERT INTO order_list (id,order_id) VALUES $order_ids";
You're explicitly combining the IDs into a string and inserting one row so the results make sense.
You need to loop through each ID submitted and attach them to a dynamically built INSERT query:
$query = "INSERT INTO order_list (id,order_id) VALUES ";
foreach ($_POST['order_ids'] as $order_id) {
$order_id = (int) $order_id; // sanitize numerical value
$query .= "(LAST_INSERT_ID(), $order_id),";
}
$query = rtrim($sql, ',');
This just illustrates a concept. There are multiple ways to do this. Just be sure you sanitize your data as your sample code is very insecure as it is wide open to SQL injection.
$query = "INSERT INTO order_list (id,order_id) VALUES (LAST_INSERT_ID(),'$order_ids')";
In SQL if you want to insert multiple rows you have to do :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
See details here
So, in your case :
INSERT INTO order_list (order_id) VALUES (123), (456)
We can avoid increment manually "id" if it's an integer autoincrement and the primary key for this table in your database.
I hope that I have made this clear.
Regards
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)));