i have searched a lot, but didn't find any solution. i want to save checkbox selected options in SQL. if user selects two check boxes thay must save in MySQL with comma separated.
Kinly please help me in solving this
HTML CODE
<input name="patno" id="patno">
<input type="checkbox" name="newt[]" value="Diesel" id="type" />Diesel
<input type="checkbox" name="newt[]" value="Petrol" id="type" />Petrol
<input type="checkbox" name="newt[]" value="Electricity" id="type" />Electricity
PHP CODE
$order = "INSERT INTO tblsampo
(patno, stno, newt)
VALUES
('$smonth',
'$patno','$stno','$newt')";
$result = mysql_query($order); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
?>
Simply implode the $_POST['type'] array like so....
$types = implode(",", $_POST['type']);
Then insert that $types variable into your table...
So...
$types = implode(",", $_POST['type']);
if($types){
$order = "INSERT INTO tblsampo
(patno, stno, type)
VALUES
('$smonth',
'$patno','$stno','$types')";}
Try this
$types = implode(',',$_POST['type']);
$sql = "INSERT INTO tblsampo
(patno, stno, type)
VALUES
('$smonth',
'$patno','$stno','$types')";
mysql_query($sql)
try the following:
$newt = false;
if (isset($_POST['newt']) && !empty($_POST['newt']) && is_array($_POST['newt'])){
$newt = implode(",", $_POST['newt']);
}
then just run your query same way but check if $myTypes is not false first
if ($newt) {
//YOUR QUERY. TIP: use PDO or MySQLi instead of MySQL_* functions
}
Related
so i tried to get data from my database to checkbox and this is what i have tried :
<?php
$query = "SELECT * FROM siswa WHERE id_tingkatan='$idtingkatan'";
$result = $koneksi->query($query);
while($row=$result->fetch_assoc()){
?>
<input type="checkbox" name="murid[]" value="<?php echo $row['id_siswa']; ? >"><?php echo $row["nama_siswa"]; ?><br><br>
<?php } ?>
and save the value of checked checkbox into database, this is what i have tried :
if(isset($_POST["submit"]))
{
if(!empty ($_POST['murid']))
{
$i= 0;
foreach($_POST as $murid){
$kelas = $_POST['kelas'];
$murid = $_POST['murid'][$i];
$query = "INSERT INTO murid (id_kelas, id_siswa) VALUES ('$kelas', '$murid')";
$q = mysqli_query($koneksi, $query) or die (mysqli_error($koneksi));
$i++;
}
}
else
{
echo "<script type= 'text/javascript'>alert('Pilih minimal 1 siswa');</script>";
header('Location: ./kelas.php');
}
}
when i submit it does input to database but theres one extra row with id_siswa value as 0
The code inserts one record for each value in $_POST. However, $_POST contains all parameters sent (including submit), not just the checkbox array to be inserted. Iterate over the checkbox array $_POST['murid'] instead.
Change
foreach($_POST as $murid) ...
To
foreach($_POST['murid'] as $murid) ...
I want the user be able to check multiple checkboxes, after which his/hers selection is printed on the html page and add each selection to my Mysql db. Unfortunately I only see the literal string 'Array' being added to my db instead of the selected names.
My script looks as follows :
<html>
<head>
<title>checkbox help</title>
</head>
<?php
if (isset($_POST['submit'])) {
$bewoner_naam = $_POST["bewoner_naam"];
$how_many = count($bewoner_naam);
echo 'Names chosen: '.$how_many.'<br><br>';
if ($how_many>0) {
echo 'You chose the following names:<br>';
}
for ($i=0; $i<$how_many; $i++) {
echo ($i+1) . '- ' . $bewoner_naam[$i] . '<br>';
}
echo "<br><br>";
}
$bewoner_naam = $_POST['bewoner_naam'];
echo $bewoner_naam[0]; // Output will be the value of the first selected checkbox
echo $bewoner_naam[1]; // Output will be the value of the second selected checkbox
print_r($bewoner_naam); //Output will be an array of values of the selected checkboxes
$con = mysql_connect("localhost","usr","root");
mysql_select_db("db", $con);
$sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('$_POST[bewoner_naam]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<body bgcolor="#ffffff">
<form method="post">
Choose a name:<br><br>
<input type="checkbox" name="bewoner_naam[]" value="kurt">kurt <br>
<input type="checkbox" name="bewoner_naam[]" value="ian">ian <br>
<input type="checkbox" name="bewoner_naam[]" value="robert">robert <br>
<input type="checkbox" name="bewoner_naam[]" value="bruce">bruce<br>
<input type="submit" name = "submit">
</form>
</body>
<html>
Thank you so much with helping me!!!
Kindest regards,
Martin
You can't insert an array into a singular column, it will show up as "array" as you're observing, so you've got two choices:
Insert multiple rows, one for each item, by looping over that array.
Combine them together using implode into a singular value.
The way your database is structured in your example it's not clear which of these two would be best.
Since $_POST['bewoner_naam'] is an array, you have to add each item in that array to the database. You can for example use a for loop for this:
$con = mysql_connect("localhost","usr","root");
mysql_select_db("db", $con);
foreach($_POST['bewoner_naam'] as $naam) {
$sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('". mysql_real_escape_string($naam) ."')";
}
Note that I've used the mysql_real_escape_string function. You will ALWAYS want to include this. For the why and how, see: Sanitizing PHP/SQL $_POST, $_GET, etc...?
First thing is to avoid all mysql_* functions in PHP. They are deprecated, and removed in newer versions, and to top it all of, insecure. I advise you switch to PDO and use prepared statements.
This will not solve your issue however. The issue you are having is that in the code where you combine the SQL you are concatenating the array with the string, that's why you only insert "Array". If you wish to insert all array items as a string, then you need to implode the array:
$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES (:checkboxes)";
$statement = $pdo->prepare($sql);
$statement->bindValue(":checkboxes", implode(",", $_POST["bewoner_naam"]);
$statement->execute();
Although, storing multiple values as a comma separated list in a database is not such a good idea, since it can become too un-maintainable through time, and produces more difficulty when obtaining such data, because you need to "re-parse" it after retrieving it from data.
As #Rodin suggested, you will probably want to insert each array item as a separate row, so I propose the following:
$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES "
. rtrim(str_repeat('(?),', count($_POST["bewoner_naam"])), ',');
$statement = $pdo->prepare($sql);
$count = 1;
foreach ($_POST["bewoner_naam"] as $bewoner_naam) {
$statement->bindValue($count++, $bewoner_naam);
}
$statement->execute();
This way you will create a bulk insert statement, with as many placeholders as there are selected checkboxes, and put each of their values on a separate line in the database.
For more on PDO, and parameter binding please refer to http://www.php.net/pdo
I would like to make a code where it get data from POST, POST contains checkbox selections (multiple selections), and the feed these data into a MySQL SELECT.
My basic code is:
echo "<form action='handler.php' method='post'>";
echo '<input type="checkbox" name="cbtest" value="10">href="details.php?id=10">data 1</a>';
echo '<input type="checkbox" name="cbtest" value="11">href="details.php?id=11">data 2</a>';
echo '<input type="checkbox" name="cbtest" value="12">href="details.php?id=12">data 3</a>';
echo "<input type='submit' name='button' value='Some action'>";
echo '</form>';
Handler.php contains:
$temp = $_POST['cbtest'];
if(isset($_POST['cbtest'])) {
foreach ($temp as $cbtest){
echo $cbtest."<br>";
}
It is clear that $cbtest variable will contain the actual POSTed data for each round of foreach command running.
But how can I catch all the data from $cbtest and run a query with a statement like this:
$query = "SELECT data_id, data_content WHERE data_id = $cbtest";
I would like to display all data_content table data for each matching iD/value in the POST variable.
How is it needed to write correctly ?
If you want multiple values for checkbox selection then make the change as follow
<input type="checkbox" name="cbtest[]" value="10">href="details.php?id=10">data 1</a>
Now in the php $_POST['cbtest'] would return array of the checked inputs. Here is the php code you need to manipulate the query.
$checkedInputs = implode(',',$_POST['cbtest']);
$query = "SELECT data_id, data_content WHERE data_id IN (".$checkedInputs.")";
PS: Please escape your inputs and change the query into a prepeared statement.
Take a look into PDO or mysqli and the prepare & execute details in the docs, below is an example.
$insert = "INSERT INTO `table` (`field1`, `field2`), VALUES (?, ?)";
$stmt = mysqli_prepare($dbConnection, $insert);
$stmt->bind_param('ss', $field1, $field2);
$stmt->execute();
// Create a PDO object
$stmt = $pdoObj->prepare($insert);
$stmt->execute([$field1, $field2]);
In insert form I am using check boxes to insert values in database. Now, I want to get checked values in edit form so I can check new values or uncheck checked values.
First I get values from database (I am using pdo, I will not post connection code to db- it works):
get oprmea from database
$sql_oprema = "SELECT Oprema FROM dbo_emarketing_stavke_oprema WHERE Partner='$id'";
$n = $conn->query($sql_oprema);
while ($r = $n -> fetch()) {
$oprema_sql = $r['Oprema'];
}
I get values when I dump variables, output is not NULL.
I am using function to store values in database. Now I want to use same function for editing if posssible.
function emarketing_oprema(){
$link = new mysqli("localhost", "root", "le30mu09", "websoft");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `dbo_emarketing_oprema` order by OpremaId asc ");
while($record = mysqli_fetch_array($sql)) {
echo '<input type="checkbox" name="oprema[]" value="'.$record['OpremaId']. '">' . $record['OpremaNaziv'] . ' <br/><br/> </input>';
}
}
I was wondering is it possible to use this function to get checked values checked.
use checked attribute
<input type="checkbox" checked>
or like this
<input type="checkbox" checked="checked">
You php will look like this:
while($record = mysqli_fetch_array($sql)) {
data='<input type="checkbox" name="oprema[]" value="'.$record["OpremaId"];
if(isset($record['checked'])) {//field in the database
data+=' checked="checked';
}
data+='">'. $record["OpremaNaziv"].'</br>';
}
I have the following code used to insert a record using PHP into a MySQL database. The form element is a multiple select that works fine when only one option is selected. When I choose more than 1 option, only the last option is inserted. How do I have the form create a new row for each option selected in the multiple select?
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "InsertForm")) {
$insertSQL = sprintf("INSERT INTO emplikons (EmpNo, IconId) VALUES (%s, %s)",
GetSQLValueString($_POST['insertRecordID'], "text"),
GetSQLValueString($_POST['icons'], "int"));
mysql_select_db($database_techsterus, $techsterus);
$Result1 = mysql_query($insertSQL, $techsterus) or die(mysql_error());
This is the code of the form element. It uses a recordset to dynamically pull values from another table:
<select name="icons" size="10" multiple="multiple">
<?php
do {
?>
<option value="<?php echo $row_icons['id']?>"><?php echo $row_icons['name']?></option>
<?php
} while ($row_icons = mysql_fetch_assoc($icons));
$rows = mysql_num_rows($icons);
if($rows > 0) {
mysql_data_seek($icons, 0);
$row_icons = mysql_fetch_assoc($icons);
}
?>
</select>
add [] to the name of the select, to get an array of all selected values.
<select name="icons[]" size="10" multiple="multiple">
Then, read from $_POST / $_GET... (assuming form method="post")
$sql = '';
foreach ($_POST['icons'] as $icon) {
// no idea where to get EmpNo from, let's assume it is in $empno.
$sql .= "('$empno','$icon'),";
}
$sql = "INSERT INTO tablename (EmpNo, IconId) VALUES " . trim($sql,',');
// Now, please use mysqli_* or PDO instead of mysql_*