I am trying to display some rows from a database table based on choices submitted by the user. Here is my form code
<form action="choice.php" method="POST" >
<input type="checkbox" name="variable[]" value="Apple">Apple
<input type="checkbox" name="variable[]" value="Banana">Banana
<input type="checkbox" name="variable[]" value="Orange">Orange
<input type="checkbox" name="variable[]" value="Melon">Melon
<input type="checkbox" name="variable[]" value="Blackberry">Blackberry
From what I understand I am placing the values of these into an array called variable.
Two of my columns are called receipe name and ingredients(each field under ingredients can store a number of fruits). What I would like to do is, if a number of checkboxes are selected then the receipe name/s is displayed.
Here is my php code.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "*****", "*****") or die(mysql_error());
mysql_select_db("****") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
echo "$variablename is checked";
}
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
foreach ($_POST['variabble'] as $ingredients)
echo $row[$ingredients] . '<br/>';
?>
I am very new to php and just wish to display the data, I do not need to perform any actions on it. I have tried many select statements but I cannot get any results to display. My db connection is fine and it does print out what variables are checked.
Many thanks in advance.
EDIT:
Thanks a million for replying. However, I tried correcting my own code=blank page and both solutions above ==blank pages also. Grrrr!! Here is one solution I tried.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
I also tried
<?php
// Make a MySQL Connection
mysql_connect("localhost", "24056", "project99") or die(mysql_error());
mysql_select_db("24056db2") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM horse WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
?>
I suppose another way to say it, if the checkbox variable is equal to a record under the ingredients column, I wish to print out the receipename of that record.
Im nearly getting confused here mysellf, haha.
Any other ideas I could try???
Correction in ur code
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
Do u see the difference above?
Place "$query" in place of "$result" mysql_fetch_assoc($result)
My Solution
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM fruit WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
Your question is not clear to me, you may try the following-
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
NOTE: This code is not tested
Related
EDIT: IGNORE ANY SQL INJECTIONS OR VULNERABLE CODE STATEMENTS :D
(School Project).
I wish to create a insert form on my webpage where I can select an artist from a table, including a song from a table and combine them for an insert into a combined foreign key table.
I have managed to do selects and insert with only individual artist and song drop-downs on my web-page, but would wish for combining the two ID's from each table to combine them to a many to many relative table. But when I press the submit button nothing happens, and I'm a beginner and don't know if I'm missing any important bits of actually Posting the information.
For troubleshooting I have tried my code, and tested it. I see if I remove my code theres no problem, so the problem persists on the syntax I believe, as the first dropdown shows, alongside the second dropdown and submit button, but the problem is within the actual processing and SQL query part, where it never goes to the DB..
The problem:
As you can see below I have a the text Song Name appear with a drop-down menu in the bottom left corner including the Artist Name with a submit button. But my problem persists as the select and then insert from the two drop downs into the combined table does not work, it does not actually submit, I want it to post into the DB what can I do. But somethings off? I would appreciate any questions or help, this community is so amazing and wonderful to operate in!
Database
PHP
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl $sql
($conn->error.";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
</form>
<input type="submit" name="mangetilmange" value ="Submit">
change you code to this:
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
<input type="submit" name="mangetilmange" value ="Submit">
</form>
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I tried inserting this into my code to generate a dropdown menu through an sql table but it responds with nothing in the dropdown. When I execute the sql query it doesn't show any error as well. Please be kind enough to fix my error. Thank you
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
$sql = "Select (unitid) from unit where (unitname)=
('$unitname')";
mysqli_query($db, $sql);
echo "<select name='unitid'>";
while ($row = mysql_fetch_array($sql)) {
echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
}
echo "</select>";
?>
Try saving the result of mysqli_query:
$result = mysqli_query($db, $sql);
And then using it in the while condition:
while ($row = mysqli_fetch_array($result)) {
The select should be also "Select unitid, unitname ..." to return also the unitname used in the options:
$sql = "SELECT unitid, unitname FROM unit WHERE unitname = '$unitname'";
And you should use prepared statements if you want to prevent it from SQL injection attacks.
If you want all the units to be shown on the combo change the select to:
$sql = "SELECT unitid, unitname FROM unit";
So, the code should be now:
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
$sql = "Select unitid, unitname from unit";
$result = mysqli_query($db, $sql);
echo "<select name='unitid'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
}
echo "</select>";
?>
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
$sql = "Select unitid, unitname from unit where unitname=\"".$unitname."\"";
$rows = array();
$return = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($return, MYSQLI_ASSOC))
$rows [] = $row;
echo "<select name='unitid'>";
for($i=0; $i<count($rows); $i++)
echo "<option value='".$rows['unitid']."'> ".$rows['unitname']."</option>";
echo "</select>";
?>
you didn't fetch the array correctly, so your query basically returned an empty array. You also wrote a wrong query. This solution should work fine
I have been looking for a solution for this for a while but they all pertain to html tables. I have a simple form and have manually added values into the database using phpMyAdmin. I have a drop down menu at the top and whenever the admin selects a particular name from the drop down menu and presses the 'Display the fields' button, I want all the respective fields to be filled in with the values after which the admin can make changes onto any particular field and update. How can I get those values to be filled? I have tried multiple codes but keep getting errors such as undefined index, undefined variable etc. Can someone help me with that?
<!doctype html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dealer_track";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed". $conn->connect_error);
}
if(isset($_POST['id1'])){
$sql = "SELECT * FROM tbl_dealer_info ";
$sql .= "WHERE $account_name = 'account_name' ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
?>
<html>
<head>
<title>iMobile </title>
</head>
<body bgcolor = "#D6DFE3">
<center><b><h2>Please enter the following information: </h2></b></center>
<form action = "dealer_track.php" method = "post">
<strong><center> <u>Fields marked with an asterisk(*) are required.</u><br><br>
Name of the dealer:* // This is where the admin selects the user they would like to update
<?php
$sql = "SELECT account_name FROM tbl_dealer_info ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'account_name' id = 'id'>";
echo "<option value = ''>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['account_name'] . "'>" . $row['account_name'] . "</option>";
}
echo "</select>";
?>
<br><br>
<input type = submit id = "id1" name = "id1" value = "Display the fields" /><br>
</center>
<hr>
<br><br>
</form>
<form action = "dealer_track.php" method = "post">
Email:*<br>
<input type = "email" name = "email" id = "id3" value = "<?php echo $row['email']?>" Required /><br><br>
RSM:*<br>
<?php
$sql = "SELECT rsm_val FROM tbl_rsm_drop_down ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'rsm_val'>";
echo "<option value = ''></option>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['rsm_val'] . "'>" . $row['rsm_val'] . "</option>";
}
echo "</select>";
?>
<br><br>
**// My radio buttons aren't getting checked though**
iPhone Boost Approved:
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="Yes")?> value = "Yes" />Yes
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="No")?> value = "No" />No<br><br>
</form>
<?php
}} // While loop and if loop at the start
?>
</body>
</html>
I'm taking a wild guess here, so I'm assuming you want to select a user from a dropdown (That could be a bad idea if many people are in said database), but you would want to make a simple HTML form and name it somethign you will remember. Under the form put this?
<?php
if(isset($_POST['formnamehere'])) {
$sql = "SELECT * FROM (table name) WHERE accountname=" . $accountname;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row['accountname'];
//put other things here, etc.
}
?>
Granted this code is not meant to be used exactly. but to give you a general idea.
You code is a bit messy but here is what you need to do generally.
First query for the unique record:
$sqlQuery = "SELECT id, firstname, lastname FROM Table Where id = '$id'";
Then run the query:
$result = $connection->query($sqlQuery ); //nb: $connection is your connection variable
Then check if any result found:
if ($result->num_rows > 0) { ........ }
If any records found then put the fetched data in variables like this
while($row = $result->fetch_assoc()) {
$firstname = $row["firstname"];
$lastname = $row["lastname"];
//and so on....
}
// You can display these variables any how you want in here, eg:
echo "<h2>$firstname</h2>";
or
<input type="text" id="firstname" name="firstname" value="<?php echo $firstname ?>" />
//nb: you must close the php tag before using html and re open it after
if "if ($result->num_rows > 0) {...} is false, just use an else {...} to display a message
You can run a query with your active connection to fetch your respective information from the table you want, along with a search clause for where the name is equal to a given value.
Query:
$result = mysqli_query($con, "SELECT `data` FROM `table` WHERE `name` = '$name';");
You can then display your data on your front end by outputting the result.
<?php
if($row = mysqli_fetch_array($result)) {
echo $row["data"];
}
?>
When I select checkbox or mulitple checkbox it only return 1 row of my database data, how to show all data from database?
<?php foreach($portControllerClass->getAllAgencies() as $port_list){ ?>
<input type="checkbox" name="port[]" value="<?=$port_list['agencies']?>"> <?=$port_list['agencies'] . '</br>';
} ?>
$date_from = date('Y-m-d', strtotime($_POST['date_from']));
$date_to = date('Y-m-d', strtotime($_POST['date_to']));
foreach($_POST['port'] as $port){
$sql = "SELECT #a:=#a+1 no, letter_no, letter_date, conformity_date,
agencies, DATEDIFF(`conformity_date`,`letter_date`) AS DiffDate
FROM info_lab, (SELECT #a:= 0) AS a
WHERE agencies LIKE '%". implode(",",$_POST['port']) ."%'
and conformity_date BETWEEN '".$date_from."'
and '".$date_to."'";
$query = $con->query($sql);
$row = $query->fetch_array();
echo $row['letter_no'];
}
You have only 1 input checkbox, so you can get only one value. To get multiple values, I think you should use foreach loop with checkbox values from database like below:
foreach ($port_list['agencies'] as $value){
<input type="checkbox" name="port[]" value="<?php echo $port_list['agencies']?>"> <php echo $port_list['agencies'] . '</br>'; ?>
}
ALso, please dont use <?= tag as it is deprecated, use <?php ?> instead
Instead of using $_POST['port'] in your query use $port.
So your query would become:
$sql = "SELECT #a:=#a+1 no, letter_no, letter_date, conformity_date,
agencies, DATEDIFF(`conformity_date`,`letter_date`) AS DiffDate
FROM info_lab, (SELECT #a:= 0) AS a
WHERE agencies LIKE '%".$port."%'
and conformity_date BETWEEN '".$date_from."'
and '".$date_to."'";
And if there is more than one row for each data then add this bit of code after $query = $con->query($sql);
if ($query->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['letter_no'];
}
} else {
echo "0 results";
}
I'm working on trying to input data from mysql into one field, below is mysql code: what I'm trying to do is have all the data from $row['db_numbers']; load into the
<input type="text" name="db_numbers" values="<?php echo $row['db_numbers'];?>
but it makes double the fields
were i end up with multiple db_number fields, I only want one.
<?php
$query = "SELECT * FROM sms_numbers WHERE `db_user` ='".$user_name."'";
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$group_sms = $row['db_numbers'];
}
?>
Try this:
<?php
$query = "SELECT * FROM sms_numbers WHERE `db_user` ='".$user_name."'";
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
WHILE($row = mysql_fetch_assoc($result)) {
$group_sms .= $row['db_numbers'];
}
?>
And then:
<input type="text" name="db_numbers" values="<?php echo $group_sms;?>">
Notice the '.=' in the while loop. It concatenates the numbers. Maybe add some spaces between them if you want ('. " "')?
WHILE($row = mysql_fetch_assoc($result)) {
$group_sms .= $row['db_numbers'] . " ";
}
Then echo the $group_sms variable since that contains all the db_numbers.
Hope that helps.
I think, if you are directly returning $row['db_numbers'] after querying the DB, then you can just print the $group_sms in the <input /> tag.
So my opinion would be:
- either return $row after querying the DB
- or directly use $group_sms in <input /> tag
If you're just trying to create an input element containing the value from a single field in the database there is no need for looping, use this:
<?php
$sql = "SELECT db_numbers FROM sms_numbers WHERE username = '$user_name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$db_numbers = $value->id;
?>
If you have multiple values that you want to concatenate or sum you could do that directly in the query and use the same code otherwise:
$sql = "SELECT GROUP_CONCAT(db_numbers SEPARATOR '') AS db_numbers FROM sms_numbers WHERE username = '$user_name'";
$sql = "SELECT SUM(db_numbers) AS db_numbers FROM sms_numbers WHERE username = '$user_name'";
Then use this to output:
<input type="text" name="db_numbers" values="<?php echo $db_numbers;?>