Php checkboxes to rows - php

I need to insert each checkbox to row in MySql.
At the moment i am able to catch only one checkbox, but I usually have them 1 - ... who knows how many..
All my checkboxes come from Db like that :
<input type="checkbox" name="lisateenus[]" value="<?php echo $row["id"]; ?>">
On insert it should take the "page id" what is created and after that insert checkbox values to table.
it gets all needed ID-s but it inserts only one checkbox what is checked..
$result = mysqli_query($con,$query);
if($result) {
$last_id = $con->insert_id;
$error = "Uus Teenus lisatud! ". $last_id;
$checkBox = implode(',', $_REQUEST['lisateenus']);
$query="INSERT INTO lisateenuse_seos (p_id, l_id, lisaja) VALUES ($last_id,'" . $checkBox . "','1')";
mysqli_query($con, $query) or die (mysql_error() );
echo "Complete";
} else {
$error = "Teenuse lisamine ei õnnestunud";}
So everything is working exept that it only inserts one row, but 3 rows are checked and should be inserted..

"each checkbox has his own ID (different) only last_id and lisaja have the same id, so each checkbox should be separate row in MySql table (after insert)"
In that case, you actually don't want to implode your checkboxes, but go through with a foreach on them:
foreach ( $_REQUEST['lisateenus'] as $somevalue ) {
$query="INSERT INTO lisateenuse_seos (p_id, l_id, lisaja) VALUES ('$last_id' ,'" . $somevalue . "','1')";
mysqli_query($con, $query) or die (mysql_error() );
echo "Complete";
}
This should insert a new row for each checked checkbox. Using implode actually makes a single string from the whole array, which then you insert only once. With foreach, you send and insert command to the sql for each ( :D ) checked checkbox.
(I added some extra quotes for the good cause.)

Related

how to update a single column of db without deleting its previous data?

i am updating a single column with many values using comma between them. they are working fine. but if update same column from other user the value inserted by previous users deleted. i want to keep values of previous user also with the insertion of new user value. and i also dont want to repeat the same value again because values i m using are unique ids..
// update student list
$venue = ($_GET['venue']);
$district = ($_GET['dis']);
if(isset($_POST['submit']))
//print_r ($_POST);
{
#$std_list=implode(',',$_POST['std_list']);
if(empty($std_list))
{
$error = 1;
$get_value = "Please select you event students.";
}
else
{
//$query = mysql_query("INSERT INTO events (std_list)
//VALUES('".$std_list."')") or die(mysql_error());
$query = mysql_query("UPDATE events SET std_list='".$std_list."' WHERE
id='".$district."' ") or die(mysql_error());
//echo "$msg";
echo "Students list submitted successfully";
}
}
if any query you can ask again. values i am inserting are integers only. Same integer cant be used by two different users.
try this?
$query = mysql_query("UPDATE events SET std_list = CONCAT( std_list, '".$std_list."') WHERE
id='".$district."' ") or die(mysql_error());

Inserting data in two columns on same row simultaneously

I have a table in a mysql database with only two columns and I want to insert data in both columns on the same row simultaneously using php. I have tried the following php script but it inserts data in the one row then the other as follows:
1-NULL
NULL-4
I want both 1 and 4 to be on the same row. Here's my php script:
<?php
$first_value = 1;
$second_value = 2;
$qry = "INSERT INTO my_table (first_value) VALUES ('$first_value')";
$qry .= "INSERT INTO my_table (second_value) VALUES ('$second_value')";
if($conn->multi_query($qry) === TRUE){
echo "success";
}
else {
echo "Error: " . $qry . "<br>" . $conn->error;
}
$conn->close();
?>
It inserts successfully. But I want the insert to be on the same row. Any help will be greatly appreciated.
just use a proper insert
$qry = "INSERT INTO my_table (first_value, second_value)
VALUES ('$first_value', '$second_value')";

2 for each statements at same time?

I recently have been trying to make a way to easily add more fields onto my form without having to go back and add more rows to my database structure. So, to begin working on this, I created a table where the structure is this:
OptionTitle
Option1
Option2
Option3
Option4
Option5
Option6
As you can see, it goes up to 6 options, and OptionTitle is the label name of the form. Then I made another table, one that reflects the users input of the previous table. This table is named usersoption
fid
OptionTitle
Option1
Ok, so FID reflects which form it is referencing to. This way, when displaying the submitted form, it'll pull information from this table where the FID is the same. OptionTitle is the label of the form, and Option1 is the option the user submitted.
Now, onto the form where it actually includes the options to select from. Here is a simplified version of how my code is included:
$query100 = $db->query("SELECT * FROM options WHERE fid='" . $id . "'");
while($row2 = mysqli_fetch_array($query100))
{
echo "
<div class=\"divform\" id=\"optiontitle\">
<label for=\"optiontitle\">$row2[optiontitle]:</label>
<select name=\"option1[]\" id=\"option1\">";
echo "<option value='$row6[option1]'>$row6[option1]</option>";
echo "<option value='$row6[option2]'>$row6[option2]</option>";
echo "<option value='$row6[option3]'>$row6[option3]</option>";
echo "<option value='$row6[option4]'>$row6[option4]</option>";
echo "<option value='$row6[option5]'>$row6[option5]</option>";
echo "<option value='$row6[option6]'>$row6[option6]</option>";
echo "
</select>
</div>
";
}
As you can see, the select name is option1[]. This is so I can have multiple select fields on the same form, and in return this will bring over the multiple difference select fields onto the submitted process. So now onto where my issue is, in the submission process. Here is what I have so far:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = 'Where OptionTitle should go', `option1` = '$val'")or die( mysqli_error());
}
As you can see, I can successfully bring the option through a foreach statement. What I can't do, is bring in the OptionTitle. It seems almost unnecessary to bring in the OptionTitle, but it is necessary for the person reading the submitted form to know which option was being submitted. I'm not sure how to carry the OptionTitle over, it seems simple but all my attempts failed miserably. I did some research and one of the suggestions was to create a hidden input with the name and carry it over that way. Here is the addon that would be in the form:
<input type=\"hidden\" name=\"optiontitle[]\" value=\"test\">
This would be added on to the form and then carried over, but the issue is how do I bring it over? I would need to do a multiple foreach statement which does not work. For example, here was what I tried to bring over (it did not work):
foreach($_POST['option1'] as $val) && ($_POST['optiontitle'] as $val2)){
$val = $db->escape_string($val);
$val2 = $db->escape_string($val2);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
Have you tried giving your option array a key?
echo "<select name=\"option1[$row2[optiontitle]]\" id=\"option1\">";
Then change your foreach to:
foreach($_POST['option1'] as $title=>$val)
You can use key in foreach to access more array:
Try this code:
foreach($_POST['option1'] as $key=>$val){
$val = $db->escape_string($val);
$val2 = $db->escape_string(isset($_POST['optiontitle'][$key])?$_POST['optiontitle'][$key]:'');
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
For the hidden input solution: Just do each query as you normally would, but add $_POST['optiontitle']:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("
INSERT `usersoption` SET
`gid` = '".$id."',
`fid` = '".$fid."',
`optiontitle` = '".$_POST['optiontitle']."',
`option1` = '$val'
")or die(mysqli_error());
}
By the way you should read up on prepared statements. These allow you to sanitise your data before inserting into the database. They are essential to good coding practise.

Insert data array in SQL after searching from another SQL table

I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.

Inserting Data from dropdown into database with PHP

First I needed a dropdown list that I could update easily so I created a database called
manufacturers where I list manufacturers to be selected in a form.
I finally accomplished this with this code:
<?php
// Connect to the test datbase on localhost
// That's where we created the countries table above
mysql_connect('localhost','##user##','##pass##'); mysql_select_db('wordpress');
// Query the countries table and load all of the records
// into an array.
$sql = 'select * FROM manufacturers';
$res = mysql_query($sql) or die(mysql_error());
while ($rec = mysql_fetch_assoc($res))
$manufacturers[] = $rec;
?>
<form action="select.php" method="post">
<?php
echo '<select name="dropdown">';
foreach ($manufacturers as $c)
{
if ($c['id'] == $_GET['id'])
echo "<option value=\"{$c['meta_id']}\" selected=\"selected\">{$c['meta_value']} </option>\n";
else
echo "<option value=\"{$c['meta_id']}\">{$c['meta_value']}</option>\n";
}
echo '</select>';
?>
<input type="submit" value="Submit" name="submit"/>
</form>
This worked out great I now have a dropdown list that is populated from my
database manufacturers.
Now I need to send this to an existing database call post_meta so that from there I can display the users selection permanently.
I have tried a couple of different options but I am trying to use the following code to send this to my post_meta database.
<?php
$con = mysql_connect("localhost","##user##","##pass##");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordpress", $con);
$sql="INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value)
VALUES
('$_POST['meta_id']}','$_POST[post_id]','$_POST[meta_key]','$_POST[meta_value]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
This actually inserts into the database but doesn't record any values.
Please help me figure out what I'm doing wrong.
The proper way to do this is to A: escape all those $_POST superglobals.
and B. Write a query as shown below.
Here's the tabledef for wp_postmeta:
http://codex.wordpress.org/Database_Description#Table:_wp_postmeta
Because meta_id is an auto_increment primary key, you do not provide it, MySQL does.
//$meta_id = mysql_real_escape_string($_POST['meta_id']); <<-- not needed.
$post_id = mysql_real_escape_string($_POST['post_id']);
$meta_key = mysql_real_escape_string($_POST['meta_key']);
$meta_value = mysql_real_escape_string($_POST['meta_value']);
$sql=" INSERT INTO wp_postmeta
(post_id, meta_key, meta_value)
VALUES
('$post_id','$meta_key','$meta_value') "; //<<-- don't forget the quotes!
if ($result = mysql_query($sql)) {
//You can get the new meta_id using:
$new_meta_id = mysql_insert_id($result);
} else {
die ("could not insert ".mysql_error());
}
Do none of your values show up? It looks like you're missing quotes around your key values. For example, shouldn't it be :
$_POST['post_id']
To do a sanity check, just echo your $_POST variables as opposed to doing the insert right away. This will help you figure out if you've got some syntax wrong. Also I'd read Brad's comment and keep it in mind for the future.
Try this query:
$sql="
INSERT INTO wp_postmeta
(meta_id, post_id, meta_key, meta_value)
VALUES
(
'{$_POST['meta_id']}',
'{$_POST['post_id']}',
'{$_POST['meta_key']}',
'{$_POST['meta_value']}'
)
";
And, as people say in comments, this code is very vulnerable, please consider to find better option to pass variables into query.

Categories