Printing two separate SQL table data on the dynamically populated table - PHP - 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).

Related

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.

How to use MySQL query results as options in HTML forms

<?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

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);

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);

How To Edit/Delete Stored Data From Database In PHP

EDIT
I have a mysql table with fields as follows:
Products - serial, name, description, price, picture.
the viewproducts.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM products ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
echo '<td> Edit</td>';
}
}
echo "</tr>";
echo "</table>";
?>
my edit.php page looks like this:
<?php
$product_id = $_GET['serial'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$product_id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
}
}
echo "</tr>";
echo "</table>";
?>
when i click on edit from thr viewproducts.php page, it goes to edit.php page where nothing is showing up. the serial id on the address bar is coming up as follows:
http://www.********.com/****/admin/edit.php?product_id=
I want to be able to edit any product clicked on from the viewproduct.php page and transfered to edit.php page. I dont think my edit.php page is set up corretly.
Please help,
Thanks
You can pass via $_GET the id of the product and then, in the edit/delete page, retrieve that parameter. Obviously you have to sanitize the input properly before using it. For example, the link of the each product should look like this:
echo '<td>Edit</td>';
In the edit page you should have something like:
$id = $_GET['id'];
// For example, if the product id is an integer
// you can sanitize it doing this
$id = (int) $id
You could pass it as an argument to your php file in wich you want to edit/delete the product:
Edit Product
Then in your edit.php you will pick up the id of the product and load it's data from the database.
[edit.php]
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : null;
if(!$product_id) {
exit();
}
// query your database for the product
$row = mysqli_query("SELECT * FROM <table> WHERE product_id = $product_id");
// then you output your html with fields populated from the result from the database

Categories