Insert Multiple Selection from Dropdown into one Row - php

I am trying to take multiple selections from a drop down, and insert them into a single column/row in a table.
So that it would look like this (ColumnB):
ColumnA | ColumnB | ColumnC
---------------------------
Stuff | A, B, C | Stuff
This is the dropdown:
echo "<select NAME='SysName_1' SIZE='1' multiple tabindex='7'>\n";
echo "<option>Choose One or More</option>\n";
To populate dropdown I use a select statement
$strSQL = "SELECT STATEMENT";
$rsSQL = odbc_exec($connSQL,$strSQL) or die ('Error Executing Subsystems SQL');
$strOptions = "";
while ($row=odbc_fetch_array($rsSQL)){
$id = trim($row["SysName"]);
$thing = trim($row["SysDesc"]);
$strOptions .= "<OPTION VALUE='$id'>$thing</option>";
}
echo $strOptions;
echo "</select>\n";
And this is what I have at my Insert:
Should combine multiple selections separated by , correct?
$SysName_1 = implode(',',$_POST['$SysName_1']);
$SQLIN = 'INSERT INTO TABLE (COLUMNA) VALUES ($SysName_1)';
I tried doing what was located here, as his code seems to be doing what I want (although he doesn't want it to) Multiple dropdown values inserting in a single row not in multiple row
But it does not work at all. I get an invalid argument for the implode in my server log, and the insert statement is just blank for that variable.
Any help would be appreciated.

The name attribute in your form needs to end with [] to indicate an array. This should work
echo "<select NAME='SysName_1[]' SIZE='1' multiple tabindex='7'>\n";
But you should be careful. Never trust user input! Don't insert the value from your $_POST directly into the db. Always escape at least

Related

How to use a dynamic dropdown created from a database to build a MySQL Query

I have built a dropdown list using PHP to show all the Unique names in my Table. I want to use that dropdown list to then use the selected value to create a MySQL Statement Dynamically.
Select * From iot_sensors WHERE Sensor_ID = ['USE the DROPDOWN MENU TO SELECT A NAME']
$select2 = "SELECT DISTINCT Sensor_ID FROM iot_sensors;";
$result2 = mysqli_query($conn, $select2);
$counter2 = mysqli_num_rows($result2);
echo "<select name ='Sensor Names'>";
while ($row = mysqli_fetch_assoc($result2)){
echo "<option value ='".$row['Sensor_ID']."'>".$row['Sensor_ID']." </option>";
}
$dynamic_query = "SELECT * FROM iot_sensors WHERE Sensor_ID = ['option value']";
echo "</select>";
I understand usually if I had manually populated the dropdown menu all I would have to do is call the option value but here the option value is on there for HTML rendering purposes.
First some warnings:
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
First, do not use names with spaces for HTML elements:
echo "<select name ='Sensor_Names'>";
Once selected and submitted (without knowing what your form method= is) the item will be in the $_REQUEST array:
$sensor_name = $_REQUEST['Sensor_Names'];
$dynamic_query = "SELECT * FROM iot_sensors WHERE Sensor_ID = '$sensor_name'";

copying value from one table to another table using dropdwon list using sql and php

i have 2 tables "cities" and "customers" with same row "city_name", i want the customer to select a city from dropdown list that Fetch its values from "cities" and store his city choice at "customers"
what i have been getting at "costumers" is a rows of 0's instead of city names, here is my code:
$query_2 = "SELECT city_name FROM cities";
$result_2 = mysql_query($query_2) or die("Query Failed : ".mysql_error());
$i_2 = 0;
while($rows_2 = mysql_fetch_array($result_2))
{
$city_name[$i_2] = $rows_2['city_name'];
$i_2++;
}
$total_elmt_2 = count($city_name);
^ here to create the list
if(isset($_POST['submit']))
{
$city_name = $_POST['city_name'];
{
^ this is to post the value
mysql_query("INSERT INTO `customers`( `city_name`)"
." VALUES ('$city_name')",$conn)
^ this is my query
<label>city <small>(required)</small></label>
<select id="city_name" name="city_name">
<option>Select</option>
<?php
for($j=0;$j<$total_elmt_2;$j++)
{
?><option><?php
echo $city_name[$j];
?></option><?php
}
?>
</select>
^ this is the dropdown list where the customer pick up his city
i hope can find someone to tell me where i went wrong in this code :(
Is the data type of your city_name column of your customers table set to varchar, text or something related to string?
You forgot semi-colon (;) after you execute your query:
mysql_query("INSERT INTO `customers`( `city_name`)"
." VALUES ('$city_name')", $conn);
^
And an opening bracket ({) after declaring your $city_name variable? Replace it with a closing bracket (}).
Does some of the data coming from customers table might have the chance of having '? Use *_real_escape_string before inserting data to your database.
$city_name = mysql_real_escape_string($_POST["city_name"]);
Use mysqli_* extension instead of deprecated mysql_* extension.

blank spaces and repetition in dropdown box

My drop down boxes are working fine using multiples of this code which, I admit, is very rudimentary:
$sql = "SELECT Country FROM engravers order by Country";
$result = mysql_query($sql);
echo "<select name\\='Country'>";
echo "<option value='$_POST'>Country</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Country'] . "'>" . $row['Country'] . "</option>";
}
echo "</select>";
The only problem is that if I have more than one item in the field I get a response for each item, for instance, in my testing database there are two rows with Australia as the country. My dropdown then puts Australia in twice. Later, when there will be about a hundred Australian entries this will be a problem.
Also if there is a blank field I get a blank line in the drop down box. I don't seem to be able to find a solution to this. Is there a better way to write the drop down code that doesn't do this. Unfortunately, as a novice, I am using the simplest code I can understand but the results look just like that. Any help would be gratefully accepted.
Try this query:
SELECT DISTINCT Country
FROM engravers
WHERE Country <> ''
ORDER BY Country
SELECT DISTINCT will take care of multiples - if there are 100 rows with Country = Australia, it will only select one.
WHERE Country <> '' will exclude any rows that have a blank value for Country. You could also include AND Country IS NOT NULL to exclude NULL values as well.
References:
<> (Not equal operator), SELECT DISTINCT ...

PHP - two multiple select dropdowns, passing user selections into a MySQL query

EDIT:
The drop down menus have the following listed in them:
Typing Course
Daily Marketing Course
When using the code below to add selected text form the dropdown into the MySQL statement, only the first word appears ie. 'Typing' and 'Daily', the code looks like this:
SELECT * FROM `acme` WHERE `course` IN('Typing', 'Daily')AND `date` IN('2010-08-27', '2010-08-31')
it should be this:
SELECT * FROM `acme` WHERE `course` IN('Typing Course', 'Daily Marketing Course')AND `date` IN('2010-08-27', '2010-08-31')
Original question below:
Hi all,
Ok, I'll do my best to explain what I would like to do.
I have two dropdown menus set to multiple, the first is Course and the second is Date, here is the code that populates each dropdown:
Course
echo "<select name='course' value='' multiple='multiple'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
echo "<option value=$ntc[course]>$ntc[course]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
Date
echo "<select name='date' value='' multiple='multiple'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($nt=mysqli_fetch_array($queryr)){//Array or records stored in $nt
echo "<option value=$nt[dates]>$nt[dates]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
The main problem I have is passing the results of each dropdown to a MySQL query. For example, if a user select from the Course dropdown 'Typing' AND 'Marketing' - I need the MySQL query to be:
SELECT * FROM acme WHERE course = 'Typing' OR course = 'Marketing'
In addition, I also need to add the second dropdown into the equation, so working on the assumption the user has selected 'Typing' AND 'Marketing', they then select 21-06-2010 from the Date dropdown, so the query then needs to be:
SELECT * FROM acme WHERE course = 'Typing' OR course = 'Marketing' AND date = '21-06-2010' OR date = '18-05-2010'
Clearly, I also need to build in if they select more than one date form the dropdown.
I hope I have explained clearly enough what I'm looking to achieve..any and all help gratefully received. Really struggling to get my head around this one.
Thanks in advance,
Homer.
Use WHERE value IN ('a', 'b'):
SELECT * FROM acme WHERE course IN ('Typing','Marketing') AND date IN ('21-06-2010', '17-09-2010');
In HTML (or the PHP that outputs HTML), add [] to fieldnames:
<select name='course[]' value='' multiple='multiple'>
in PHP:
$courses=$_POST['course'];
$courses=array_map('mysql_real_escape_string', $courses);
$dates=$_POST['date'];
$dates=array_map('mysql_real_escape_string', $dates);
$query = 'SELECT * FROM `acme` WHERE ';
$query.='`course` IN(\''. join("', '", $courses). '\')';
$query.='AND `date` IN(\''. join("', '", $dates). '\')';
OK, first of all, your SQL is a bit off. Rather than WHERE course = 'Typing' OR 'Marketing', you want WHERE course = 'Typing' OR course = 'Marketing'. Alternatively, you could use WHERE course IN ('Typing', 'Marketing'). You can then create this using the array_map function to add the quotes and the join function to link them together:
<?php
...
function escape_and_add_quotes($string) {
return '\'' . mysql_real_escape_string($string) . '\'';
}
...
$sql = 'SELECT * FROM acme WHERE course IN (' . join(',', array_map('escape_and_add_quotes', $courses)) . ')';
?>

How to I pull information from MySQL with PHP?

I am asking if it is not only possible to pull data from a MySQL table, but also display each row in either a table or a DIV, preferably a DIV. How would I do so?
Table:
ID |BodyText |Title |
1 |Hello World1 |Title1 |
2 |Hello World2 |Title2 |
etc..
I'd like to put each row into a DIV that has a title and also bodytext, but I want php to generate these tables and put the info into each DIV.
Possible to do?
We will use this table as an example data set:
Database Name: friends
-----------------------------
| firstname || lastname |
----------------------------
|Chris || Geizz |
|Steve || Michalson |
|Ken || Bohlin |
|Doug || Renard |
-----------------------------
First you must connect to your database as so:
http://www.w3schools.com/PHP/php_mysql_connect.asp
You would run a MYSQL query to get the data from the MySQL Database:
$query = mysql_query("SELECT * FROM friends");
Then you would use the following to put them into a table:
echo "<table><tr><td>First Name</td><td>Last Name</td></tr>";
while($row = mysql_fetch_array($query))
{
echo "<tr><td>";
echo $row['firstname'];
echo "</td><td>";
echo $row['lastname'];
echo "</td></tr>";
}
echo "</table>";
What this basically does is pulls the information that is returned with my mysql_query and puts it into an array that you can call with the $row variable we set. We do this in the while loop so that it repeats for all records in your database.
The code before the while loop and after the while loop are there so that way it is all in one table and we are just making rows instead of separate tables for each row in your database.
This will accomplish what you want. When you are doing the while loop you can use the variables ($row['firstname'] and $row['lastname']) as you wish. You could place them in seperate DIV's if you wish as well.
Hope this helps you! If you have any questions leave a comment and I will respond.
Basically you can do whatever you want, once you have the rowset. The general structure of such code (if layers not devided / MVC) looks like this:
connect to db
write query
retrieve results
loop for each row in resultset
{
echo html and column content as you wish
}
so for example you could use
foreach ($rowset as $row)
{
echo '<div>'.$row['column1'].' is a friend of '.$row['column2'].'</div>';
}
Here's the manual pages for how to access/query MySQL databases:
MySQL: http://www.php.net/manual/en/book.mysql.php
MySQLi: http://www.php.net/manual/en/book.mysqli.php
Using the functions there you can easily query and display the data as you see fit. If you are wanting to access column info (field names) you either need to use the access the information_schema tables or use queries like describe table.
Update: based on the comments, the question relates more to Tharkun's answer than this.
<?php
$result = mysql_query("SELECT * from table");
if($result && mysql_num_rows($result))
{
$numrows = mysql_num_rows($result);
$rowcount = 1;
while($row = mysql_fetch_assoc($result))
{
print "<div><b>$rowcount</b>";
foreach($row as $var => $val)
{
print"|$var: $val|";
}
print "</div>";
++$rowcount;
}
}
?>

Categories