php: get option select value by mysql - php

I'm trying to have an altas.php file for various html forms. This code is a html form with some mysql columns:
<div><label for="categoria">Categoría principal</label><select type="text" name="categoria">
<?php
$query = "select id, categoria from categorias";
$result = mysqli_query($mysql,$query);
if(!$result) echo 'Muy mal....';
$num_filas = mysqli_num_rows($result);
for ($i = 0; $i < $num_filas; $i++){
$row = mysqli_fetch_array($result);
?>
<option value "<?php echo $row['id']?>"><?php echo $row['categoria']?></option><?php
}
?>
</select></div>
On the other hand, if I make this:
foreach($_POST as $campo => $valor){
echo $campo ." = ". $valor ."\n";
}
I have no data in $row['categoria']. It should return the value, which is the categorias's id.
Another question:
How can I use the "foreach" whith an insert sentence?
For example:
foreach($_POST as $campo => $valor){
$query ="INSERT INTO $tabla ($campo) VALUES ('$valor')";
}
$tabla is sent via $_GET. This code make a new row for each $campo. Any idea?
I have try some suggestions, but nothing works.

You seem to be missing an = and closing semi-colons on this line:
<option value "<?php echo $row['id']?>"><?php echo $row['categoria']?></option><?php
Should be:
<option value="<?php echo $row['id']; ?>"><?php echo $row['categoria']; ?></option><?php
EDIT:
Also removed type from select list

Related

PHP- is unable to read the other checked checkbox

I stored the data in a supposed to be an array but what happens is that only the last checked checkbox is the only one that is registered in the idSkills. This is the part of the code wherein the skills are displayed through a query in the database
<?php
$i=0;
while ($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills[]" value="<?php echo $id; ?>"><?php echo $skillName; ?><br>
<?php
$i++;
}
?>
Here is the part where the loop unveil all of the selected checkbox
//QUERY TO INSERT
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
$idSkills = $_GET['skills'];
if(empty($idSkills))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($idSkills);
echo("You selected $N door(s): ");
echo("$idSkills[1] ");
for($i=0; $i < $N; $i++) {
echo "Skill ID: "
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('$idSkills[$i]','$idVolunteer')";
$result = $conn->query($sql);
}
}
$conn->close();
It would be best to use a prepared statement instead of substituting a variable into the SQL. But if you're going to do it this way, you need to use the correct syntax:
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('{$idSkills[$i]}','$idVolunteer')";
You need to put {} around an array reference in order to get the variable inside the brackets to be evaluated. See the section on Complex (curly) Syntax in the PHP Strings documentation.

PHP passing Array

I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}

How to output a row from table and insert all the row data in the option tag

I am new in programing and i have stuck in one piece.
Well I have 1 database, in that database I have some teams, my goal is to put those teams in a option tag where I can modify the team. Thanks all!
$sql_grupi = "select grup_name from grupi";
$res_grupi = mysqli_query($dbCon, $sql_grupi);
$res_array = array();
if (!$res_grupi) {
die("Error");
}
while ($row = mysqli_fetch_array($res_grupi, MYSQLI_ASSOC)) {
$res_array[] = $row['grup_name'];
}
down here is my form where i call the table data
<select name="grupi">
<option value="<?php $res_array; ?>"><?php $res_array; ?></option>
</select>
you can do it through loop array:
echo '<select name="grupi">';
while ($row = mysqli_fetch_array($res_grupi, MYSQLI_ASSOC)) {
echo "<option value='".$row['grup_id']."'>".$row['grup_name']."</option>"
}
echo '</select>';

PHP Select List - Insert multiple values in database

I'm trying to insert multiple values in the database using select list. What I got so far:
HTML
<form enctype="multipart/form-data" action="" method="post">
<select name="cars[]" multiple="multiple" style="width:300px">
<?php
$getcars = mysql_query("SELECT cars_id, cars_name FROM car");
while ($row = mysql_fetch_assoc($getcars)) {
$car_id = $row['cars_id'];
$car_name = $row['cars_name'];
?>
<option value="<?php echo $car_id ?>"><?php echo $car_name ?></option>
<?php } ?>
</select><br />
<input type="submit" name="submit" value="Submit"/><br/>
</form>
PHP
$cars= $_POST['cars'];
echo $cars;
for($i = 0; $i < count($cars); $i++){
echo $cars[$i];
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
}
Unfortunately it doesn't work, I tried to print $cars to check the resulted value. It prints "Array", and when I tried to print $cars[$i] it prints nothing.
Does anyone know what the problem is?
There is an extra closing bracket that should be removed. You are not checking if your query was successful or not.
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
should be:
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]')") or die(mysql_error());
Since $cars is an array, you can print its content using print_r or var_dump:
print_r($cars);
var_dump($cars);
Useful reading:
How to get useful error messages in PHP?
mysql_* functions are deprecated
You have error $cars[$i]] and need change $cars[$i]
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
fix php for you with good sql
$cars= $_POST['cars'];
echo $cars;
foreach($cars as $i => $cars_name){
echo $cars_name;
$carGroups = mysql_query("INSERT INTO car_groups SET `fieldcompany`='{$company}', `fieldcars`='{$cars_name}'");
}

Dynamic PHP Dropdown Menu for Countries

Okay so I have a table called Countries and it looks like this:
---------------------------
|Country | Code |
---------------------------
|Afganastan | AF |
|ÅLAND ISLANDS| AX |
| etc. | etc. |
---------------------------
The thing that I want to do is create a dynamic menu in which the user chooses a country and that itself gets stored as a value that I can call after the user hits submit.
I did try something here but I'm not sure what its doing because I am still new to PHP and HTML to the point where I just type things in to see what would happen.
Anyways I am really stuck and I tried using google and the search feature in this site and nothing I found worked for me...
The code I tried is this:
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
</select>
The result is supposed to look like a dropdown menu with the list of countries from the database in it. But this doesn't work and just shows this in the drop down:
.$row['name']
Which is nothing close to what I want because that's not even a country. when I remove that part of the code, then there is no option for the user to choose, the menu is empty.
EDIT
My code so far that still doesn't work:
<select name = 'country'>
<?php
include ("account.php");
include ("connect.php");
$result = mysql_query('SELECT Code , Country FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['Code']?>"><?php echo $row['Country']?></option>
<?php}
?>
</select>
The include ("account.php"); and include ("connect.php"); lines allow me to connect to my database.
you code should be something like this
$host = "localhost";
$user = "root";
$pass = "yourpassword";
$db = "databasename";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = #mysql_connect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
#mysql_select_db($db);
<form method = "POST" action = "abc.php">
<select name = 'country'>
<?php
$result = mysql_query('SELECT id , name FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['id']?>"><?php echo $row['name']?></option>
<?php}
?>
<input type = "submit" value = "Submit">
</form>
Now in php use this
echo '<pre>';
print_r($_POST);
And you will see what user selected. Check your settings there might be some problem.
Your single and double quotes are messing you up:
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
should be:
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
You can use a single quote around your script but when you jump out of it to do the $row['id'] and $row['name'] you are running into issues because it thinks you are jumping back into your quoted code... Either use my example above, starting/ending with double-quotes and escaping all double-quotes inside that need to display, or escape your single quotes in the $row[\'id\'] and $row[\'name\']
Thant should help you out.
Try this code
<?php
$result = mysql_query('SELECT * FROM Countries');
?>
<select name="country">
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
Firstly your table doesn't have a column id. Try changing your query like
SELECT Country, Code FROM Countries
Then the code and the html should be like this
<?php
$host = "localhost";
$user = "user"; //username
$pass = "pass"; //password
$db = "db"; //database
$con = #mysql_connect($host, $user, $pass);
if ( !$con )
{
echo "Error connecting to database.\n";
}
#mysql_select_db($db);
?>
<select name="country">
<option value="0" selected="selected">Choose..</option>
<?php
//echo '<select name = \'country\'>';
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
?>
</select>
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
$row = mysql_fetch_array($result)
for ($i=0; $i<count($row ); $i++)
{
echo '<option value="'.$row[$i]['id'].'">'.$row[$i]['name'].'</option>';
}
echo '</select>';
?>
next page use print_r($_POST);
or var_dump($_REQUEST);
If you are using mysql_fetch_array you can use either the field names or their selected index to read them from the fetched row. You can also use either the sprintf or printf functions to merge content into a string to help keep the HTML fragment clean of the quotes needed to merge in values otherwise.
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result)) {
printf('<option value="%1$s">%2$s</option>',
$row['Code'], $row['Country']);
}
Your SQL statement selected only 'Country' from the 'Countries' table; as a result, it's impossible for you to use $row['id'] and $row['name'].
Use this instead:
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
echo '</select>';
?>
That should solve your problem.
I figured out the problem I was having. The first being that there was an extra select tag in the page and the second that the file was saved as a html page instead of a php file. Thank you to everyone that helped me figure this out!
Try my code, I'm using this and it really works... just change the values...
<?php
include ('connect.php');
$sql = "SELECT * FROM casestatusfile";
$result = mysql_query($sql);
echo "<select name = 'txtCaseStatus'/>";
echo "<option value = ''>--- Select ---</option>";
$casestatus = $_POST['txtCaseStatus'];
$selected = 'selected = "selected" ';
while ($row = mysql_fetch_array($result)) {
echo "<option " .($row['CASESTATUSCODE'] == $casestatus? $selected:''). "value='". $row['CASESTATUSCODE'] ."'>" . $row['CASESTATUS'] ."</option>";
}
echo "</select>";
?>
I'm sure that is working because that is the one that i'm using....

Categories