Insert an array and show value in PhpMyAdmin - php

I am using checkboxes to see if a user wants "Breakfast,Dinner and Supper"
This is my code for that
<div id="checkboxesFood">
<p>Please select if you want breakfast, dinner and supper</p>
<input type="checkbox" class="food" name="foodboxes[]" value="Breakfast"/>Breakfast
<input type="checkbox" class="food" style="margin:0 0 0 19%;" name="foodboxes[]" value="Dinner"/>Dinner
<input type="checkbox" class="food" style="margin:0 0 0 19%;" name="foodboxes[]" value="Supper"/>Supper
</div>
I'm using PHP to connect to a DB and store the value there.
This is my PHP code
$username = $_POST['userName']; //Username
$view = $_POST['roomChoice']; //View Of Room
$paymentMethod = $_POST['payment']; //How user want's to pay
$selectedFood = $_POST['foodboxes']; //Food they have selected(Breakfast, Dinner or Supper)
//$foodData = array($selectedFood);
$con = new mysqli('localhost','username','mypw','DB');
if($con->connect_error){
die("Connection failed: " .$con->connect_error);
}
//$implodedData = implode(",",$foodData);
$sql = "INSERT INTO Hotellbokning(Name,Room,Food,Payment) VALUES('$username','$view','$implodedData','$paymentMethod')";
if($con->query($sql) == true){
echo "You did it John!";
}
else{
echo "Error: " . $sql . "<br/>" .$con->error;
}
Just ignore the variables that is not an issue. When I insert this array $selectedFood into my DB, I recieve the value "Array" on my Food-field.
Is there a way to see the value of this array(the three values Breakfast,Dinner and Supper) in PhpMyAdmin, or is it only possible to echo them out from my DB?
P.S. I tried using implode but it didn't work. I've also tried $foodData = array($selectedFood) But it didn't work either.

You're imploding the wrong thing. $selectedFood is already an array, you don't need to wrap it in another array. So it should be:
$implodedData = implode(',', $selectedFood);
Then you can store $implodedData in the database.
However, putting comma-separated lists in a database is generally poor design. You should use a relation table with a separate row for each item.

Related

How can I populate a 3rd column result on intersections of 1st and 2nd columns all from the same table that are selected by the user on dropdown?

I have a column vehicle_name and I would like 2 dropdown lists of my 2 other columns namely, vehicle_type and vehicle_color.
When these 2 dropdown values are selected and submitted, I would like their intersection to print out the values from vehicle_name. So far my code only generates a dropdown list for vehicle_type, I would need another dropdown for vehicle_colour. Which on submissions populates the intersected values for the vehicle_name. How can I achieve this?
<!DOCTYPE html>
<html>
<body>
<?php
echo "<br>";
echo "<br>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$db = new mysqli($servername, $username, $password, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<br>
<div class="label">Select vehicle type:</div>
<select name="payment_method">
<option value = "">---Select---</option>
<?php
$queryusers = "SELECT DISTINCT vehicle_type FROM orders";
$db = mysqli_query($db, $queryusers);
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['vehicle_type']."}'>".$d['vehicle_type']."</option>";
}
?>
</select>
<br>
<div class="label_for_time">Select color:</div>
<select name="vehicle_color">
<option value = "">---Select---</option>
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
</select>
<br>
<br>
<button class="go-btn" type="submit">Go</button>
</body>
</html>
As I don't see any AJAX / client-side code in your above example I assume that this is a pure backend-side filtering you are performing. Your code is currently missing parts of the required elements we would need but let's try to figure this out together:
1. Form around your inputs
Add a <form method="POST" target="path-to-your-script.php"> where "path-to-your-script.php" has to be changed to your PHP file name or rewritten URL path. This has to be around the <select> boxes.
You may also use PHP_SELF to set this automatically, this should work in most cases. I used html_entities($var) to avoid any code injections via manipulated URL.
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
2. Check for POST'ed variable 'vehicle_type'
In your form, check if a search for available colors has been performed:
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
// check if the form variable 'vehicle_type' is available; if so, filter entries.
if (isset($_POST['vehicle_type'])) {
$vType= filter_var($_POST['vehicle_type'], FILTER_SANITIZE_STRING);
$query_for_colors .= ' WHERE vehicle_type = \''.$vType.'\'';
}
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
Edit:
As pointed out by one user in the comment, filter_var($var, FILTER_SANITIZE_STRING) won't be enough to avoid potential SQL injections. This was just a recommendation and was not part of the question at all. If you have to work with user data, do more than using filter_var(), instead use either prepared statements or properly escape the user data. There are many tutorials like this one out there that will guide you to safe queries.

How to do multi-part PHP query of mysql db

I have read through hundreds of posts on here and on other sites. I am not overly familiar with PHP and mysql, but already have my tables built in mysql, have called them using single checklists and filtered them based on date and time. However, in the multi-checkbox arena, I cannot seem to pin down what I'm doing wrong for an array code and customizing the resulting table. This is the basic html:
<html> <body> <form method="POST" action="php/minute_feedback.php">
Date: <input type="text" name="from_date" id="from_date" value="2016-04-07">
<input type="checkbox" name="check_list[]" value="gate" id="gate">
<input type="checkbox" name="check_list[]" value="pressure" id="pressure">
<input type="checkbox" name="check_list[]" value="flow" id="flow">
<input type="submit" name="submit" value="submit">
This is the basic PHP (I'll only include the date parameters vs. date & time to keep it shorter since the inclusion will be the same):
<?php
$servername = "myhostaddress.com";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabasename";
$conn=new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
if($_POST['submit'] == "submit") {
$from_date = ($_POST['from_date']);
$to_date = ($_POST['from_date']);}
if(isset($_POST['submit'])) {
Now ... I know there should be some sort of an array code in here like:
$checklist[] = $_POST[check_list];
But - I'm not sure what the correct syntax/code is.
Next question is about my query. I've seen most queries using a WHERE + IN combo and a '*' for SELECT. However, I need something closer to:
$sql = "SELECT Fdate, Ftime, (list of variable columns from the checked options such as 'gate', 'pressure', 'flow' --> but only if they've been checked) FROM minute_db WHERE Fdate BETWEEN '$from_date' AND '$to_date'";
$result = $conn->query($sql);}
if ($result->num_rows > 0) {
Now - as for my table headers, I can use the following code if I had a single value being looked up:
echo "<table><tr><th>Date</th><th>Time</th><th>Level (ft)</th></tr>";}
But, I need the header to be dynamically populated with the results of the checked items (1, 2, or 3 or more variables as needed) plus the date and time records.
echo "<table>";}
else {
echo "0 results";}
$conn->close();
?>
My end result is that the user can enter a date and time range and choose which data to display, so for example, if they want to know just the gate setting and pressure on 4/7/2016, they'd enter that date and check those two boxes so they will get a table (no formatting below - just trying to represent), for example:
Date | Time | Gate Setting | Pressure
----------------------------------------------------
2016-04-07 | 11:00 | 21 | 50
I will ultimately have a table with tens of thousands of rows of data to select from (and will include limiters to the amount of data that can be pulled), and up to 56 columns of variables to select from. I'm not using any special/fancy math functions to group time periods, etc. - I've already manually separated it all out and uploaded it so it's ready to go. I've tried a lot of different solutions from the internet, but have ultimately failed. The * option for SELECT doesn't seem like what I what, neither does the IN option - but I am not sure (just speculating as neither has worked). I'm on a netfirms mysql platform, so it's pretty updated (and I'll be changing everything to mysqli to avoid whatever problems stem from not using it - so any feedback with that in advance would be AWESOME!!. I appreciate any ideas you have!
Thanks to Deep's solution above - it works perfectly as-is! AWESOME. As for the use of the table array, I was struggling because I could populate the table, but was getting duplicates of date and time (as noted in my replies above). However - I simply moved the script around a bit and it works. Now, the user will get back columns with the date, time, and then the additional variables they are looking for, side by side, across the page, as comparative values (note - I have not yet gotten to the point of mysqli or pdo, so if this is old, please update as you need). Hopefully this helps - and thanks again! So - from the sql line from Deep's post above (fully filled out), this is the table -->
$sql = "SELECT Fdate, {$wantedFields} Ftime FROM minute_db WHERE Fdate BETWEEN '$from_date' AND '$to_date' AND Ftime BETWEEN '$from_time' AND '$to_time'";
$result = $conn->query($sql);
}
if ($result->num_rows > 0) {
//header fields
echo "<table><tr><th>Date</th><th>Time</th>";
foreach($tableDynFields as $c) {
echo "<th>$c</th>";
}
echo "</tr>";
//results
while ($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["Fdate"]."</td><td>".$row["Ftime"]." </td>";
foreach($tableDynFields as $c) {
echo "<td>".$row[$c]."</td>";
}
echo "</tr>";
}
echo "</table>";
//result set free
$result->free();
} else {
echo "query failed.<hr/>";
}
$conn->close();
?>
The only thing I'll add is if you're having to filter and sort through as much data as I am - tis good to either put a forced limiter at the end of the select statement, or something to that effect!
$checklist = $_POST['check_list'];
$allowedFields = [
'gate' => 'Gate',
'pressure' => 'Pressure',
'flow' => 'Flow',
'etc' => 'Other field title'
];
$wantedFields = [];
$tableDynFields = [];
foreach ($checklist as $field) {
if (array_key_exists($field, $allowedFields)) {
$wantedFields[] = $field;
$tableDynFields[] = $allowedFields[$field];
}
}
if ($wantedFields) {
$wantedFields = join(',', $wantedFields) . ',';
} else {
$wantedFields = '';
}
$sql = "SELECT Ftime, {$wantedFields} Fdate FROM ...';
// and here you have $tableDynFields array for table generation

How to add multiple selection checkboxes to mysql db?

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

Get values checked

I am having trouble in getting checked values checked in form. I was trying to use the same function as I have used to insert values to print all values in edit form, and which are in other table inserted to mark them checked.
Function to insert values in database table in insert form and it works.
function emarketing_usluge(){
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `jos_ib_emarketing_oprema` order by OpremaId asc ");
while($record = mysqli_fetch_array($sql)) {
echo '<input type="checkbox" name="usluge[]" value="'.$record['OpremaId ']. '">' . $record['OpremaNaziv'] . ' <br/><br/> </input>';
}
}
In this function I get list of all services and place them in checkboxes.
Now I want to edit form, and display all values that are checked by using same function.
First I make query to get values, I am using here pdo but for funcion files I have used mysqli.
Form for editing!
$sql_oprema = "SELECT a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";
$oprema = $conn->query($sql_oprema);
$row = $oprema ->fetch();
<div class="col-xs-6">
<input type="checkbox" id="oprema" onclick="Exposeoprema()">Oprema<br>
<div id="Scrolloprema" style="height:150;width:200px;overflow:auto;border:1px solid blue;display:none">
<?php
while($row = $oprema ->fetch()) {
$data='<input type="checkbox" name="oprema[]" value="'.$row["Oprema"].'"';
if(isset($row['Oprema'])) {//field in the database
$data.=' checked="checked';
}
$data.='">'. $row["OpremaNaziv"] .'</br>';
}
emarketing_oprema($data);
?>
</div>
</div>
I am trying print all service values by using function, but the ones that are checked they need to have check mark. I am getting problem and could not figure it out how to solve it.
Looking back to your SQL query, I don't see an extraction of checked field, you are not selecting it. So there is never going to be a $row['checked'] element of your query.
You should add:
$sql_oprema = "SELECT a.checked, a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";

update database by text box based on the checked box's

**Hi
i have been working on this php code .
I want to update the quantity that belongs to the checked box .
but the exact problem with my code is :if I have for example 3 checkboxs and when I enter the quantity for them all in the same time the updates are done correctly and if I only update the first quantity with out the other 2 the update is done correctly also ,But when I update the second or the third alone not in the same time it takes the quantity of the old value of the first :""(
so how can I change my code so I can update all the items or only the checked items.
here is my code to display the checkbox's with the quantity.
in the file manage_items.php :**
<?php
$DB_HOST ='localhost';
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='dks';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if(!$con){
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if(!$db){
die("unable to select database");
}?>
$qry="SELECT * FROM catalog";
$result= mysql_query($qry);
if($result){
while($info = mysql_fetch_array($result))
{
print "<h3> cat:".$info['name']."</h3><div>";
$qryitem="SELECT * FROM item WHERE Id=". $info['Cid'];
$resultitem=mysql_query($qryitem);
if($resultitem){
?>
<form method="post" action="manage_item_action.php">
<?php
while($info=mysql_fetch_array($resultitem))
{
?>
<input type="checkbox" name="op[]" value="<?php echo $info['Id'];?>"/><?php echo $info['name'];?>
<label> Quantity <input type="text" name="Quantity[]" value="<?php echo $info['Quantity'];?>"/></label>
<br/>
<?php
}
}
else echo "There are no items.";
print "</div>";
}
}
?>
</div>
<input type="submit" value="update" name="submit"/>
</form>
and here is the excution of update
in the file manage_item_action.php
<?php
$DB_HOST ='localhost';
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='dks';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if(!$con){
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if(!$db){
die("unable to select database");
}
$options=$_POST['op'];
$qun=$_POST['Quantity'];
$size =count($options);
for($i =0; $i<$size; $i++)
{
//$qryop="UPDATE item SET Quantity =".$qun."WHERE Id =".$options[$i]."';";
$resultop=mysql_query("update item set Quantity='".$qun[i]."'where Id='".$options[$i]."'");
}
if($resultop){
header("location: manage_items.php");}
else echo "there was an error"
?>
i dunno how to fix the problem !
but i think my main problem is that all the textbox's have the same name .
so when i send it to the other file for ecution it just take it as it is the last one .
help me please :$
*UPDATED*
*The Solution*
so I solved the problem of my code and its only needed the textbox to be disabled before checkin the checkbox so the array doesn't have any null index..only have the entered values without any nulls
:))
You need to give the 'Quantity' input field a unique name or cast it as an array for every checkbox listed, else when submitted the receiving form will take the last value for 'Quantity' as gospel.
That's because in your input form box, you have:
Quantity <input type="text" name="Quantity" ...
So, with each of the quantity inserted, the forwarded values are being updated. And the last value inserted into Quantity box will be taken in update. Instead, change this form input to this:
<!-- This will forward an array to php script -->
Quantity <input type="text" name="Quantity[]"...
and then, in your updation query, change to:
$resultop=mysql_query("UPDATE item SET Quantity='" . $qun[$i] . "'where Id='".$options[$i]."'");

Categories