PHPMyadmin checkboxes displays "Array" - php

I've searched extensively but can't find an answer… Hope someone can help:
I'm a newbie PHP and MySQL user and have a problem with checkboxes.
I have a simple HTML page which contains checkboxes.
The page is linked up to a MySQL db in PHPmyadmin.
The HTML is:
<html><p>User1<input type="checkbox" name="Users[]" id="Users1" value="1"/></p>
<p>User2<input type="checkbox" name="Users[]" id="Users2" value="2"/></p>
<p>User3<input type="checkbox" name="Users[]" id="Users3" value="3"/></p>
<p>User4<input type="checkbox" name="Users[]" id="Users4" value="4"/></p></html>
What I want is for the person filling in the form to check 1 or more of the values and then for the checked values to be displayed in PHPmyadmin, so that I can export them.
However, when using this PHP:
$values = implode(',', $_POST['Users']);
All I get in PHPmyadmin is "Array", and I can't figure out how to get the actual values to be displayed.
Thanks in advance,

You can get all value checked by looping :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
echo( ($i+1) . ") " . $userChecked [$i] . "<br/>");
}
This will display all id. Instead of echo the value you can insert them in your database or do what you want. The values will be loop inside : $userChecked [$i]
#Daok: Yes, that displays the values
on the results page, but in
PHPmyadmin, it still indicates
"Array". How do I get it to display
the values?
PhpMyAdmin is just a tool to administrate php/mysql. I guess you mean that you have "array" written in your database? If you do want all value inside a field (varchar) than you just have to implode:
$comma_separated = implode(",", $_POST['Users']);
//Code here to Insert to you database with ...value($comma_separated)...
If you want 1 row for each entry :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
//Insert Sql statement here with value($userChecked [$i])
}

try
$values = implode(',', (array)$_POST['Users']);
or
Users=array();
$values = implode(',', $_POST['Users']);

Related

PHP - Build PDO Query Parameters from multiple checkbox form

I am trying to build a PHP PDO query, based from a set of checkboxes that a user has selected on the previous page.
So i have the following checkboxes in my form:
<input type="checkbox" name="websites[]" value="one" id="one">
<input type="checkbox" name="websites[]" value="two" id="two">
<input type="checkbox" name="websites[]" value="three" id="three">
Once submitted i then want to build a pdo query and query parameters based from what checkboxes the user selected - they have to all be in the one query though. I know that any checked boxes will be stored in my $_POST['website'] array but how can i then take that and put them in the query? For example say the user selected one and three only, i then want to only select those fields from my database table:
$results = $_POST['websites'];
$query = "
SELECT
one,
three
FROM
table
";
How can i do the above?
First of all you should use a white-list of allowed fields to avoid sql injection. Then you need to check every sent-in entry to see if it exists in your white-list and add it to the query if it does.
So something like:
$allowed_fields = array(...);
$fields = array();
// only checked fields are sent to the server
foreach ($_POST['websites'] as $value)
{
if (in_array($value, $allowed_fields))
{
$fields[] = $value;
}
}
$query = 'SELECT `' . implode('`, `', $fields) . '` FROM table';

how do you store multiple rows and column array in mysql

I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}

Parse CSV From HTML form and Insert into MYSQL Database

I'm trying to take an array and insert it into seperate rows in a MYSQL database.
Basically, there's an HTML form for a top 5 list that I want to input in one field, but with each value seperated by commas. So, for example (Artist 1, Artist 2, Artist 3, etc.)
These 5 values then have to be seperated into 5 values that are then inserted into 5 rows in a MYSQL database.
So the HTML form looks like this:
<tr>
<td>Loud Rock</td>
<td><label for="lr_topfive"><input type="text" placeholder="" name="lr_topfive" size="75"
maxlength="100" autofucus required /></label></td>
</tr>
and the form value is sent to another php file with this code in it:
$val = $_POST['lr_topfive'];
$data = str_getcsv($val);
??????
$lr_one = mysql_prep($_POST['lr_one']);
$lr_two = mysql_prep($_POST['lr_two']);
$lr_three = mysql_prep($_POST['lr_three']);
$lr_four = mysql_prep($_POST['lr_four']);
$lr_five = mysql_prep($_POST['lr_five']);
$query = "INSERT INTO xyz_wb (lr_one, lr_two, lr_three, lr_four, lr_five) VALUES ('{$lr_one}','{$lr_two}', '{$lr_three}', '{$lr_four}', '{$lr_five}')";
$result = mysql_query($query, $connection);
if ($result) {
redirect_to("email-ready.php");
} else {
//display error message
echo "<p>Yikes!</p>";
echo "<p>" . mysql_error() . "</p>";
}
I get that the 'lr_topfive' value is parsed and seperated into distinct values by the first two lines, but I dont know what to do before inserting these values into the MYSQL DB.
I think you are just looking for:
$top_five_array = explode(',', $_POST['lr_topfive']);
and then:
$lr_one = mysql_prep($top_five_array[0]);
$lr_two = mysql_prep($top_five_array[1]);
....
However, this will break if there are not exactly 4 comma's in your input field.
Apart from that you need to switch to prepared statements using PDO or mysqli, see the comments below your question.

how to retrieve checked values in php

I am a newbie in php. I have a form with multiple checkbox values. I wanna retrieve the checked values and diplay these values on other php form.
Below is the code which works perfectly fine if we add the checkboxes without while loop.
But when added through while loop I am not able to fetch the selected items.
xyzhtml.php(html form)
<?PHP
require ("DBConnect.php");
$selectQuery =mysql_query( "SELECT * FROM fruits where approved = 0");
while($row = mysql_fetch_array($selectQuery))
{
$fruit_name = $row['fruit_name'];
echo "<input type=\"checkbox\" name=\"things[]\" value=\"$fruit_name\">";
echo "<br>";
}
?>
On click of submit I call other php clled "xyz.php".
Below is the code used in it.
<?php
$checkBox = $_POST['things'];
echo $checkBox[0];
for($i=0; $i<sizeof($checkBox); $i++){
echo($checkBox[$i]);
}
?>
Please help.
Thanks in advance.
two things to check:
are you getting right values from the MySQL SELECT statement (check your HTML for empty checkboxes values and check your MySQL database for fruits that have approved field set to 0 to see if there are any)
when you don't tick a checkbox and submit the form, unticked checkboxes' values do not get submitted - have you thought about that?
Use foreach to record $_POST['things']
if (!empty($_POST['things'])) {
foreach ($_POST['things'] as $value) {
echo "the value are: ".$value;
}
}
Note: teh $_POST['things'] not $_POST['things[]']
I think your code should work, but it won't display anything if no checkboxes are selected.
I would however remove the explicit echo $checkbox[0] (unless this is for testing purposes).
Try a print_r($checkbox) to see what's actually in that array.

How to check a check box if it's value is in DATABASE. PHP

I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.

Categories