How to use MySQL query results as options in HTML forms - php

<?php
$con = new mysqli('localhost', 'root' ,'', 'world');
$query = 'SELECT * FROM city ORDER BY Name';
if ($result = mysqli_query($con, $query)) {
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>"
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
mysqli_close($con);
?>
This simple code will display every entries in this database. Now I would like to add a selective display option by choosing the CountryCode.
$query2 = 'SELECT DISTINCT CountryCode FROM city ORDER BY CountryCode';
How do I use the result I got from the query above and make it become radio buttons to choose what to display?

Similar to what you are doing already: Something like
while ($row = mysqli_fetch_assoc($result)) {
echo "<input type='radio' name='whatever' value='".$row['Name']."'>". $row['Name'];
}
Ofcourse the field names can be whatever you like them to be, as long as you select them in the query

Related

how to Insert multiple checkbox values of array into database

I am stuck with how to insert multiple array data of checkbox. I came across some code but I don't know how to implement them in my php code. How can I insert multiple data from checkbox in my database? Can someone help me? I really appreciate it. Thank you in advance.
html code:
<?php
include ('connect.php');
$sql2 = "SELECT * FROM owner WHERE owner_username ='".$_SESSION['username']."'";
$result2 = mysqli_query($conn,$sql2);
$row = mysqli_fetch_array($result2);
$id = $row['owner_id'];
$sql = "SELECT cat_id,name,gender,health_status,neutered,breed,color,age
FROM cat WHERE owner_fk = '$id'";
$result = $conn-> query($sql);
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
echo "<tr>";
echo "<td>" .$row ['name']. "</td>";
echo "<td>" .$row ['gender']. "</td>";
echo "<td>" .$row ['health_status']. "</td>";
echo "<td>" .$row ['neutered']. "</td>";
echo "<td>" .$row ['breed']. "</td>";
echo "<td>" .$row ['color']. "</td>";
echo "<td>" .$row ['age']. "</td>";
echo "<td>" ."<input type='checkbox' name= 'check[]' value=''". "
</td>";
echo "</tr>";
}
echo "</table>";
}
else{
echo "0 result";
}
$conn-> close();
?>
this is my php code:
<?php
include ('connect.php');
if(isset($_POST['submit']))
{
for($i=0;$i<count($_POST["check"]);$i++)
}
$p_id =$_GET ['sitter'];
$price = $_POST ['price'];
$pickup_date =$_POST ['pickup_date'];
$dropoff_date =$_POST ['dropoff_date'];
$numdays = $_POST ['numdays'];
$total =$_POST ['test'];
$sql2 = "INSERT INTO cat_sitter(sitter_fk,cat_fk, price, date_in,
date_out,total_day, total)VALUES ('$p_id','".$_POST["check"]
[$i]."','$cat_id','$price','$pickup_date','$dropoff_date','$numdays',
'$total')" or die ("Error inserting data into table");
if ($conn->query($sql2) === TRUE) {
echo "<script language='javascript'>alert('Succesfully Book.')
window.location.replace(\"book_page.php\");
</script>";
}else{
echo "error: " . $sql2 . "<br>" . $conn->error;
}
?>
Use implode function
In your case replace $_POST["check"] with implode(',',$_POST["check"]) then it will work fine fine hope so
Instead of implode and explode. You can use convert checkbox array into JSON and store in single field.
// Convert Array to JSON String
$checkArray = $_POST["check"];
$checkJSON = json_encode($checkArray);
After you fetch its value from database convert JSON into array.
// Convert JSON string to Array
//$checkJSON is variable fetched from database
$checkArray = json_decode($checkJSON, true);
print_r($checkArray); // Dump all data of the Array

How to check if a result array element is present in another result array

I have this code in my program:
<?php
session_start();
$_SESSION['user_id']=201102887;
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
die("not ok");
}
mysqli_select_db($con,"uoh");
$q = "SELECT * FROM courses
INNER JOIN transfer_student_courses
ON transfer_student_courses.course_number = courses.course_number
INNER JOIN transfered_courses
ON transfer_student_courses.sn = transfered_courses.sn
AND transfer_student_courses.student_ID = " . $_SESSION['user_id'];
$result = mysqli_query($con , $q);
if($result){
echo "<table>";
echo "<tr>";
echo "<th>equivalent</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["equivalent"]. "</td>";
echo "</tr>";
}
echo "</table>";
}
mysqli_select_db($con,"uoh");
$q = "SELECT * FROM courses
LEFT JOIN degree_plan
ON degree_plan.course_number = courses.course_number
LEFT JOIN student_record
ON courses.course_number = student_record.course_number
AND student_record.id = ". $_SESSION['user_id']."
WHERE degree_plan.major = 'COE'
ORDER BY term_no";
$result = mysqli_query($con , $q );
if($result){
echo "<table>";
echo "<tr>";
echo "<th>course</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo "</tr>";
}
}
echo "</table>";
?>
I have two queries in this code, each of which give me a list of courses.
If a course appears in the first list, I do not want it to appear in the second list.
If you see the output of this code below, the first query gives me MATH 101, and the second query also gives me MATH 101.
I want MATH 101 to not appear in the second course list because it also appears in the first list.
How can I write a function in PHP language to do that?
Output:
equivalent
MATH 101
course
PHYS 101
CHEM 101
PE 101
IAS 101
MATH 101
ENGL 101
First of all, store all the equivalent courses in an array, say $equivalent array. And then in the second while loop use in_array() function to check if the course already got printed in the first table or not.
Here's the reference:
in_array()
So your code should be like this:
<?php
session_start();
$_SESSION['user_id']=201102887;
$con = mysqli_connect('localhost', 'root', '');
if(!$con){
die("not ok");
}
mysqli_select_db($con,"uoh");
$q = "SELECT * FROM courses INNER JOIN transfer_student_courses ON
transfer_student_courses.course_number=courses.course_number INNER
JOIN transfered_courses ON transfer_student_courses.sn=transfered_courses.sn
AND transfer_student_courses.student_ID = " . $_SESSION['user_id'];
$result = mysqli_query($con , $q) ;
$equivalent = array();
if($result){
echo "<table>";
echo "<tr>";
echo "<th>equivalent</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$equivalent[] = $row["equivalent"];
echo "<tr>";
echo "<td>" . $row["equivalent"]. "</td>";
echo "</tr>";
}
echo "</table>";
}
mysqli_select_db($con,"uoh");
$q = "SELECT * FROM courses
LEFT JOIN degree_plan ON degree_plan.course_number= courses.course_number
LEFT JOIN student_record ON courses.course_number= student_record.course_number
AND student_record.id= ". $_SESSION['user_id']."
WHERE degree_plan.major='COE' ORDER BY term_no";
$result = mysqli_query($con , $q ) ;
if($result){
echo "<table>";
echo "<tr>";
echo "<th>course</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
if(in_array($row["code"], $equivalent)){
continue;
}
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo "</tr>";
}
}
echo "</table>";
?>
You could load the results of the first query into an array, then when you are displaying the results for the second query, before you display anything check if the result exists in your array, if it does, skip it.
So after your first query:
$equivalent = array(); // Setup a blank array to store the results
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["equivalent"]. "</td>";
echo "</tr>";
$equivalent[] = $row['equivalent']; // Add the result into your array
}
Then in your courses portion of code:
while($row = mysqli_fetch_array($result))
{
if ( ! in_array($row['code'], $equivalent ) )
{
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo "</tr>";
}
}
This should stop the display of any entry that is in both result sets being displayed in the second.
HTH
Solution : in_array("word", $array)
Run a query get the result into an array :
while($row = mysqli_fetch_array($result))
{
arr1[]=$row["code"];
}
For the second query run the query and add reults as follows:
while($row = mysqli_fetch_array($result)){
if (in_array($row[code], $arr1))
{
//don't add to array2
}
else
{
arr2[] = $row["code"];
}
}
Then you may echo the elements as required.

select SQL table from php variable

I have selected a random table from a list/array and I want to be able to call this random table with the mysqli_query function i.e. select a table dynamically
Here is my code:
<?php
$mysqli=mysqli_connect(HOST,USERNAME,PASSWORD,DATABASE);
// Check connection
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Looks at all prodcuts and selects those that have special offers enabled
// Selects a random table from the array
$tables_special = ["ajbs_products_console" ,"ajbs_products_console_games", "ajbs_products_pc", "ajbs_products_pc_games", "ajbs_products_pc_parts"];
$rtable = $tables_special[floor (rand(0,count($tables_special)-1))];
echo "<p>".$rtable." was selected</p>";
$products = mysqli_query("SELECT * FROM '".$rtable."'");
echo "<p>".$products."</p>";
while($productRow = mysqli_fetch_array($products))
{
if ($productRow['product_specials'] == 1)
{
echo "<table>";
echo "<tr>";
echo "<td rowspan='2'><img src=" . $productRow['product_image'] . "/></td>";
echo "</tr>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>" . $productRow['product_name'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Description</td>";
echo "<td>" . $productRow['product_description'] . "</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($mysqli);
?>
Im at a loss of why this is not working
Thanks,
Bull
You should not quote table names with single quotes but with backticks, single quotes makes it a string instead of a table name;
Also, the function mysqli_query takes an extra parameter, the connection.
$products = mysqli_query("SELECT * FROM '".$rtable."'");
should be;
$products = mysqli_query($mysqli, "SELECT * FROM `".$rtable."`");
Try
$products = mysqli_query($mysqli, "SELECT * FROM ".$rtable);

Printing two separate SQL table data on the dynamically populated table - PHP

Can someone please help me on the following code? Simply put, I'm trying to get two separate SQL tables' data, one on the horizontal side (brands) and the other (distributors) on the vertical side of a dynamically populated table.
my issue is, if you go through the code I cant get the text boxes populated under each respective brand name I get to display from the database. The text boxes are appearing only for the first brand name column.
My second issue if how do I assign a unique ID or a name to a dynamically populated text box here?
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$sqlq="SELECT * FROM brands";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
$resultq = mysqli_query($db,$sqlq) or die ("SQL Error_er2");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
while($rowq = mysqli_fetch_array($resultq))
{
echo "<td>" . $rowq['bname'] . "</td>";
}
"</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='txt1'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
You're creating loop without relating to eachother, and the same goes for the execution of the querys...
If you want to solve it you will have to nestle the loops together, something like:
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
//Go through all distributors
while($rowq = mysqli_fetch_array($result)) {
echo "<td>" . $rowq['bname'] . "</td>";
//Show all brands for current distributor
$sqlq="SELECT * FROM brands where distributor_id = " . $rowq['rsm'];
$resultBrands = mysqli_query($db,$sql) or die ("SQL Error Brands");
while($row = mysqli_fetch_array($resultBrands))
{
$id = $row['rsm'];
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
//End show all brands for current distributor
}
//End Go through all distributors
A better solution though, would be something like (of course $q has to validated before input inside of query and also binded with bind_param()).
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql = " SELECT * FROM distributors d";
$sql .=" LEFT JOIN brands b ON (d.brand_id = b.brand_id)";
$sql .=" WHERE d.rsm=$q";
$result = mysqli_query($db,$sql) or die ("SQL Error");
echo "<table border='1'>";
while($rowq = mysqli_fetch_array($result))
{
$id = rowq['rsm'];
echo "<tr>";
echo "<td>" . $rowq['dname'] . "</td>";
echo "<td>" . $rowq['bname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
Take notice of the name='textBox[]'. From PHP you can access the variable with $_POST['textBox'] (or $_GET['textBox'] and PHP will return an array).

How to order by higher id sql

I have rows in MYSQL.
They are basically articles and rumours based on user input. In my query, i would like the table created to have the later results ranked higher. How would that Order By Query work?
$query = "SELECT * FROM rumours";
$query.= "ORDER BY"
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$band = $row['band'];
$title = $row['Title'];
$description = $row['description'];
echo "<table border='1'>";
echo "<tr>";
echo "<td> $title </td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'> $description </td>";
echo "</tr>";
echo "</table>";
}
Few things regarding your snippet.
Use a column list and avoid selecting *
mysql_ functions are being deprecated. You should use either mysqli_ or PDO functions.
You can save yourself time by calling your columns directly, rather than reassigning them variables.
When you are asking for the older records to display first, what is the criteria for this? Does a higher id mean the record is newer? I've assumed this in my answer.
Here's an improved version of your code using mysqli_:
$link = mysqli_connect("localhost", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$q = "SELECT id, band, Title, description FROM rumours ORDER BY id DESC";
$result = mysqli_query($link, $q);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "<table border='1'>";
echo "<tr>";
echo "<td>" . $row[id] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'>" . $row[description] . "</td>";
echo "</tr>";
echo "</table>";
}
mysqli_free_result($result);

Categories