I have this sql statement that gets user input from a form and stores the values in the database
foreach ($_POST["name"] as $key => $name) {
$sql = "INSERT INTO test_table(name,price) VALUES ('".$name."','".$_POST["price"]."')";
$mysqli->query($sql);
}
In my database, I get the correct name value but on the price field I get an array. Is there a way to get the value of the POST['price']?
you need to loop through the price too
If you are getting values from a single form do you need to pass them individually
you can create an array like this
$form_field = array($_POST["name"], $_POST["price"]);
foreach($form_field as $field => $value){
$sql = "INSERT INTO test_table(name,price) VALUES ('".$value[0]."','".$value[1]."')";
$mysqli->query($sql);
}
Try this out and see
Related
I have an array of data that I would like to insert into my SQL database (table), I then want to be able to fetch it as an array in a separate file. I have no idea how to put it in as an array and get it back out as an array
This is for a contract, I have already tried inserting it as a string and then getting it out as an array but that doesn't work
$added = $_POST['added']; // this is the array
foreach ($added as $addedArr){
}
and I tried inserting $addedArr
That's the only code i can really show, I'm very stuck.
Using PDO (guide), for example, you could execute a query with an array, giving you a few options.
One such option would be to execute numerous queries with each sub-array, such as:
foreach ($arrays as $array) {
$query = $database->prepare('SELECT name, color, calories FROM fruit WHERE calories < ? AND color = ?');
$query->execute($array);
}
Another option would be to flatten out your array and do a multi line query like so:
$flat_array = []; //The array that will contain all the values of the main array of data
$query = 'insert into fruit (name, color, calories) values '; //Build the base query
foreach ($arrays as $array) {
$query .= '(?, ?, ?),'; //Add in binding points to the query
foreach ($array as $value) $flat_array[] = $value; //Add each value of each sub-array to to the top level of the new array
}
$query = $database->prepare(substr($query, 0, -1)); //Prepare the query, after removing the last comma
$query->execute($flat_array); //Execute the query with the new, flat array of values
You would then be able to pull out the data into an associative array later on with that same guide.
I have a dynamic HTML form with three fields (item, number, cost). Users can add as many rows as they need. Because of this, I have set the fields names as item[], number[], cost[] in order to loop through the post and insert the values in the DB.
I have verified that the values are posted correctly up correctly through vardump, and I have checked that the following loop is picking up the values (both key and value) through printr. (and also simply echoing $value1).
foreach ($_POST as $field => $value) {
foreach($value as $field1 => $value1){
echo $field . ':' . $value1 . '</br>' ;
}
};
However, if I try insert passing the values to execute, nothing happens (no data is inserted and I get no error message).
if($_POST['submit']){
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT INTO invoice (item, number, cost) VALUES (?,?,?);');
foreach ($_POST as $item => $value) {
foreach($value as $item1 => $value1){
$stmt->execute($value1);
}
}
$pdo->commit();
}
catch (Exception $e){
$pdo->rollback();
throw $e;
}
}
I know that $value1 holds the correct values, but they are not being inserted. Can anyone help?
I have tried:
https://phpdelusions.net/pdo_examples/insert#multiple
PDO insert statement with loop through $_POST array
PDO insert array values Insert multiple rows using form and PDO
Need php pdo implode arrays and insert multiple rows in mysql
As your $_POST array contains columns you need to get values from the corresponding cells, i.e. for the first row you need items[0], number[0] and cell[0] and so on. So iterate over the first column, get the index and use that index for the other two
foreach ($_POST['item'] as $i => $item) {
$stmt->execute([$item, $_POST['number'][$i], $_POST['cost'][$i]]);
}
I'm trying to load a multi numbers(rows) to a database from a form. Anyone can help with the code?
$n = $_POST['txtname'];
foreach ($a as $value) {
$sql = "INSERT INTO Sheet1 VALUES($value)";
You need to initialise an array with the data before using the foreach loop.
You should use the following format:
//Obtain values from form text boxes
$name = $_POST['Name'] //This must match the name input on your form
//Populate values into array
$arrayData = array('$name'); //Can also populate with multiple values..
//Query
foreach ($arrayData as $value) {
$sql = "INSERT into table_name (table_column_name) VALUES($value)";
}
Sources: http://www.w3schools.com/sql/sql_insert.asp
http://bbrown.kennesaw.edu/papers/php2.html
I have a table that was dynamically created using jquery. Now I am sending the inputs, that are array, of course, to a database. The fields are customCLASSE[], customQTY[], customPRICE[]... and this is my script that inserts the data within MySQL:
if ($_POST['customCLASSE']) {
foreach ( $_POST['customCLASSE'] as $key=>$value ) {
$query = $mysqli->query("INSERT INTO booking_multiday_detail (classe) VALUES ('$value')");
}
}
It is working very good but my question is: How do I insert the other inputs (customQTY[], customPRICE[]...) within the same foreach in the same time that customCLASSE is being inserted?
$key is the index of array on looping cycle.
So if your other arrays sorted as well as customCLASSE you can access other arrays' value by $key like this,
if ($_POST['customCLASSE']) {
foreach ( $_POST['customCLASSE'] as $key=>$value ) {
$customQty = $_POST['customQTY'][$key];
$customPRICE= $_POST['customQTY'][$key];
//change the query
//....
$query = $mysqli->query("INSERT INTO booking_multiday_detail (classe) VALUES ('$value')");
}
}
I have a PDO update query gets the $_POST (or any other key-value array) and writes up the UPDATE query in respect to the inputs given.
I have an exclude array that I can specify keys to not include in the SQL query, such as the submit key and value of the form (action_update_survey, in this case.).
I create the SQL query by iterating through the array via foreach to firstly create the query and insert the parameter placeholders and secondly to bind the parameters to the parameter placeholder within the query.
Here is my code:
function save_survey($post){
global $pdo;
$exclude_names = array('action_update_survey');
$wp_userid = get_current_user_id();
$update_survey_query = "UPDATE kwc_surveysessions SET ";
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)) $update_survey_query .= $key." = :".$key.", ";
}
$update_survey_query = rtrim($update_survey_query, ", ")." WHERE wp_userid=:wp_userid";
$update_survey = $pdo->prepare($update_survey_query);
print_r($update_survey_query);
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)){
$update_survey->bindParam($key, $value);
}
}
$update_survey->bindParam("wp_userid", $wp_userid);
$update_survey->execute();
}
After executing my function following a post, all text columns in my database are set to the value 'Save', which is the value of the submit input, of name *action_update_survey*, which is strange, because it should be excluded from both foreach loops, which assign the keys and values.
Printing the PDO query before executing shows that there's been no setting of the excluded input anywhere in my query:
UPDATE kwc_surveysessions SET s1q1 = :s1q1, s1q2 = :s1q2, s1q7 = :s1q7, s1q8 = :s1q8, s1q9 = :s1q9, s1q10 = :s1q10, s1q11 = :s1q11, s2q6 = :s2q6, s3q7 = :s3q7 WHERE wp_userid=:wp_userid
Any idea what would be causing the submit input to push its value into all my fields?
The most probable cause is that bindParam() passes values by refference.
Try using an array like this:
arr = array();
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)){
arr[$key] = $value;
}
}
$update_survey->execute($arr);
and use "arr" to execute the query.