Following PHP code is working fine when only ONE set of array values in POST ie, on index value 0...When index value is greater than one, duplicate entries are getting inserted into the table..please help...
$sql = "INSERT INTO js (s_name, s_age, s_marks, s_school) VALUES ";
foreach($_POST as $objResult)
{
$i = 0;
foreach($objResult as $Result){
$i++;
if($i>1)// add ',' after first set of values in INSERT..
{
$sql .= ",";
}
$name = $Result['sname'];
$age = $Result['age'];
$mark = $Result['mark'];
$school = $Result['school'];
$sql .= "('".$name."','" .$age."','".$mark."','" .$school."')";
$result=$conn->query($sql);
}}
You can completely eliminate any issues with all of that iterating you have going on by doing something like this:
foreach($_POST as $objResult) {
foreach($objResult as $Result) {
$sql .= "(" . implode(', ', $Result) . "),";
}
}
$result=$conn->query($sql);
And now do you notice how I moved the query out of your loops? That makes sure that you run it properly and not on every iteration (loop) of the data.
Here is a working Example (You will have to press ctrl + enter to run the code)
You need to move the
$result=$conn->query($sql);
out of the inner loop, you are not clearing the string, so it will keep adding in the entries added already.
Thank you for your suggessions. And I changed my code as following..
$sql = "INSERT INTO js (s_name, s_age, s_marks, s_school) VALUES ";
foreach($_POST['student'] as $Result)
{
$name = $Result['sname'];
$age = $Result['age'];
$mark = $Result['mark'];
$school = $Result['school'];
$sql .= "('".$name."','" .$age."','".$mark."','" .$school."'),";
}
$sql = rtrim($sql,",");
$result=$conn->query($sql);
you can change code like this
foreach($_POST as $objResult) {
foreach($objResult as $Result) {
$sql .= "(" . implode(', ', $Result) . "),";
}
}
$result=$conn->query($sql);
Related
I need to be able to save selected items from a multi select drop-down list into a MySQL DB and display all the selected items. When I hit submit only the last item is saved.
Code originally was for a single item to be selected from a drop-down menu. I have modified it for selecting multiple items (for ease of editing by other people). I have tried various solutions including if is_array, for loops and foreach loops without any luck. Can anyone point me in the right direction please.
HTML code
<select name="topic_id[]" multiple="multiple" id="select">
<?php
$topic_set = find_all_topics();
while($topic = mysqli_fetch_assoc($topic_set)) {
foreach($topic_set as $topic) {
echo "<option value=\"" . $topic['id'] . "\"";
if($page['topic_id'] == $topic['id']) {
echo " selected";
}
echo ">" . $topic['menu_name'] . "</option>";
}
}
mysqli_free_result();
?>
</select>
PHP
function insert_page($page) {
global $db;
$errors = validate_page($page);
if(!empty($errors)) {
return $errors;
}
shift_page_positions(0, $page['position'], $page['topic_id']);
$post_t_ids = array();
foreach($_POST['topic_id'] as $post_t_id) {
$post_t_ids[] = (int) $post_t_id;
}
$post_t_id_joined = join('), (', $post_t_ids);
$sql = "INSERT INTO pages ";
$sql .= "(topic_id, content) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $post_t_id_joined) . "',";
$sql .= "'" . db_escape($db, $page['content']) . "'";
$sql .= ")";
$result = mysqli_query($db, $sql);
if($result) {
return true;
} else {
echo mysqli_error($db);
db_disconnect($db);
exit;
}
}
if(is_post_request()) {
$page = [];
$page['topic_id'] = $_POST['topic_id'] ?? '';
$page['content'] = $_POST['content'] ?? '';
$result = insert_page($page);
if(!isset($_POST['topic_id'])) {
$_POST['topic_id'] = [];
}
if($result === true) {
$new_id = mysqli_insert_id($db);
} else {
$errors = $result;
}
}
The result should be selecting multiple items from the drop-down list and upon clicking submit all selected items should save to the DB and displayed to a different page. No error messages pop up but only the last item selected gets saved and displayed.
Your part to make an sql statement is wrong. It will produce you something like:
INSERT INTO pages (topic_id, content) VALUES ('1), (2), (3','content')
You need to modify your code to get a proper sql statement. Of course, I would recommend you to use prepared statements:
$params['content'] = $page['content'];
$stmt = $mysqli->prepare('INSERT INTO pages (topic_id, content) VALUES (:id, :content)');
foreach($_POST['topic_id'] as $id) {
$params['id'] = $id;
$stmt->execute($params);
}
If you still want to use your approach, you should do it like this:
$content = $page['content'];
$makeValues = function($id) use ($content) {
return "($id, '$content')";
};
$post_t_id_joined = implode(', ', array_map($makeValues, $post_t_ids));
$sql = "INSERT INTO pages ";
$sql .= "(topic_id, content) ";
$sql .= "VALUES $post_t_id_joined";
I am looking for a way to make dynamic queries to my MySQL server. At the moment this is the code I use to update data on the server:
$deskAttr = json_decode($_POST["desk_attributes"]);
foreach($deskAttr as $key => $value) {
$sql = "UPDATE desk_attributes SET iw_standard=".$value->iw_standard.", avaya_standard=".$value->avaya_standard.", avaya_withcallid=".$value->avaya_withcallid.", avaya_withtransfer=".$value->avaya_withtransfer.", dual_screen=".$value->dual_screen.", air_conditioning=".$value->air_conditioning.", iw_obdialler=".$value->iw_obdialler." WHERE id=".$value->id;
$conn->query($sql);
}
As you can see, the SQL column names are the same as thedeskAttrkeys. I'm looking for a way to make this line a loop so, that I don't need to change this line if I were to add more columns to the MySQL table.
It would look something like this:
$deskAttr = json_decode($_POST["desk_attributes"]);
foreach($deskAttr as $key => $value) {
$sql = "UPDATE desk_attributes SET";
foreach($value as $k => $v) {
$sql .= " $k = $value->$k ,";
}
$sql .= "WHERE id=".$value->id";
}
How would I write the code above so it will actually work?
**EDIT**
Maybe it will be helpful to know that$deskAttr is an array of objects, and the name of the columns are the same as the name of the objects keys.
Here is what I mean in pseudo code:
foreach($object in $deskAttr) {
$sql = "UPDATE table SET ";
foreach($key in $object) {
if($key != "id")
$sql .= "$key = $object->$key, ";
}
$sql .= "WHERE id = $object->id;
$conn->query($sql);
}
Obviously this would add an extra comma at the end of the query before the WHERE part, but hopefully you get what I'm trying to achieve.
You can do it with slight change in your code by using PHP's implode() function.
Take a blank array, concatenate the update parameters to it.
And then if is not empty(), implode() to get string.
Updated Code:
$sql = "UPDATE desk_attributes SET ";
foreach ($deskAttr as $key => $value) {
$value = mysqli_real_escape_string($link, $value); // $links is database connection string.
$key = mysqli_real_escape_string($link, $key); // $links is database connection string.
$updtAttrs[] = $key ." = '" . $value . "'";
}
$sql .= ! empty($updtAttrs) ? implode(', ', $updtAttrs) : '';
$sql .= " WHERE id=" . $value->id;
I need to parse the following code and process the resulting data.
foreach($job as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
The above code is returning the following as expected.
Key=vca_id, Value=20130<br>Key=uuid, Value=3c87e0b3-cfa<br>Key=originate_time, Value=2013-03-15 14:30:18<br>
What I need to do is to put the values in mysql database. So the insert statement would look something like this...
insert into test.master_table (vca_id, uuid, originate_time) values ('20130', '3c87e0b3-cfa', '2013-03-15 14:30:18')
What is the correct way to save the array values to mysql database?
<?php
mysql_query("insert into test.master_table(vca_id, uuid, originate_time)values('".$job['vca_id']."','".$job['uuid']."','".$job['originate_time']."')");
?>
Well i will recommend implode
$keys = array();
$values = array();
foreach($job as $x => $x_value)
{
$keys[] = $x;
$values[] = $x_value;
}
$query = 'INSERT INTO test.master_table' . '('.implode(',',$keys) .') VALUES (' .implode(',',$values) . ')';
You can try this
$temp_value_arr = array();
$query = "INSERT into test.master_table SET ";
foreach($job as $x=>$x_value)
{
$query .= "$x = '$x_value',";
}
$query = rtrim($query, ',');
mysql_query($query);
I have 2 checkboxes. Their values go to another php file and if any of them is checked, its value is inserted mysql codes. I did it, but when the number of checkbox increase and more advanced things appear, my code will be impossible to put into practise.
Here is checkbox.php :(it is inside a form)
<div>
<label>Choose:</label>
<label>Camera </label><input type="checkbox" name="kind[]" value="1" />
<label>Video </label><input type="checkbox" name="kind[]" value="2"/>
</div>
when the form is clicked, it goes to fetch_kind.php via AJAX and jquery($.post).
Here is code:
<?php
$kind = array();
$kind = $_POST['kind'];
$count = count($kind);
if ($count== 0) {
echo "You did not checked any of checkboxes!!!";
}
if ($count == 2) {
$sql = "SELECT id,kind FROM products";
} else {
foreach ($kind as $value) {
if ($value =="1") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
if ($value =="2") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
}
}
?>
Could you give a better example? Thank you...
A simple way would be to group all the values and us IN
if ($count > 0){
$sql = "SELECT id,kind FROM products WHERE kind IN (" . implode (',', $kind) . ")";
}
Also you might want to look into sanitizing you input.
You can loop through all your checkboxes and add a simple condition to an array. You implode the array at the end.
Something like:
$conds = array();
foreach ($kind as $value) {
$conds[] = '`kind` = ' . intval($value);
}
$sql = "SELECT id,kind FROM products WHERE " . implode(" OR ", $conds);
I am just a beginner in php. I used the following code to display the user names fetched from the database.
$select_tl = "SELECT `varTeamleader` FROM `tbl_team` WHERE `intTeamid` = '" . $id . "'";
$select_tl_res = mysql_query($select_tl);
$select_tl_num = mysql_num_rows($select_tl_res);
if ($select_tl_num > 0) {
$fetch_tl = mysql_fetch_array($select_tl_res);
$tl = $fetch_tl['varTeamleader'];
$sep_tl = explode(",", $tl);
foreach ($sep_tl as $key => $value) {
$sel_tlname = "SELECT * FROM `tbl_user` WHERE `intUserid` = '" . $value . "'";
$sel_tlname_res = mysql_query($sel_tlname);
$sel_tlname_num = mysql_num_rows($sel_tlname_res);
if ($sel_tlname_num > 0) {
$fetch_username = mysql_fetch_array($sel_tlname_res);
$user_name = $fetch_username['varName'];
echo $user_name . ", ";
}
}
}
I need to echo the user_name with comma after every value but not after last one. How can i do that?
Add the items to an array and then implode(',', $arr).
After you're done iterating, remove the last comma. That's an easy way of doing it.
$user_name=substr($user_name,0,-2)