Select elements from 2 different tables to put in a php loop - php

I'm making a web site for a business and in the "car list" I would like to take information from 2 tables of my data base, one for the car info (name, price...) and the other one for the images URL table.
Example of my code:
$mysqli = new mysqli("localhost","root","","database") or die("1");
$sql = "SELECT * FROM cars WHERE type= '".$cartype."'";
$result = $mysqli->query($sql);
if($result)
{
while($row = $result->fetch_assoc())
{
?>
<table>
<tr>
<td> HERE IMAGE URL FROM TABLE 2 </td>
<td> <?php echo $row['name']; ?> INFO FROM TABLE 1 </td>
</td>
</table>
<?php
}
}
How can I connect to table 2 and put the info in my while loop?
Thanks a lot.

You are going to have to join your two database tables in your select query. To do that you need an id in your photos table that links it to your cars table.
Example:
$sql = "SELECT name,url FROM cars,photos WHERE cars.id = photos.car_id AND type= '".$cartype."'";
Then use
$row['name']; $row['url'];

Related

How to compare two SQL database table and mark checkbox based on result using php

Hope you are doing great. So I am working on a automated attendance system using face recognition and I am displaying data through php.
I have a SQL database with the name of student_db and there are two tables in it with the name of mark_attendance and student_detail. Face recognition system recgnize faces and send rollnumber and date on mark_attendance
enter image description here
where as student_detail consist of whole class students name and rollnumber.enter image description here enter image description here
I am displaying name, rollnumber and a checkbox on frontend what I want to do is to mark checkbox aUtomatically if student is present. It should compare data of mark_attendance table with the studet_detail table and mark checkbox.
I AM ATTACHING THE CODE I HAVE TRIED BUT ITS NOT WORKING.
<html>
<head></head>
<body>
<table border="1">
<tr>
<th> Name </th>
<th> Attendance </th>
</tr>
<?PHP
include('db_connection.php');
$qry = "SELECT * FROM student_detail";
$result = mysqli_query($db_con, $qry);
$ftch = mysqli_fetch_assoc($result);
$markattendance = "SELECT * FROM mark_attendance ";
$ma = mysqli_query($db_con, $markattendance);
if(mysqli_num_rows($result) > 0)
{
foreach($result as $r)
{
$sav = "SELECT * FROM mark_attendance t1
JOIN student_detail t2
ON t2.rollno = t1.rollno";
$sa = mysqli_query($db_con, $sav);
$s = mysqli_fetch_assoc($sa);
$count = mysqli_num_rows($sa); echo "</b>";
echo "<table><tr>";
echo "<td>".$r['Name']."</td>";
// echo $r['rollno'];
echo $s['rollno'];
if($count >= 1 && $s['rollno'] == $r['rollno']){
echo "<form><td> <input type='checkbox' checked value=".$r['Name']."></td>";
}
else{
echo "<form><td> <input type='checkbox' value=".$r['Name']."></td>";
}
// echo "<form><td> <input type='checkbox' value=".$r['Name']."></td>";
// echo "<td> <input type='text' value=".$r['rollno']."></td></form>";
echo "</tr>";
}
}
?>
</table>
</body>
</html>
Its MARKING only the first data checkbox on db not other after it.
I also have tried with while loop and other stuff but its still not working can you run it on your computer and provide me the working code.
SORRY FOR THE BAD ENGLISH

Printing of data

I created 3 tables in my database "Colleges" in PhpMyAdmin. The names of the tables are "cool", "data" and "tab". The first table "cool" consists of the the names of the states of India. It has two columns : ID and Statename. From the data in this table, I created a drop down list in HTML form. Further the HTML form consists of the name, email id, contact and the address. The user has to fill in the details and select his/her state from the drop down list. Now, the user input consisting of name, email id, contact and the address goes into the second table "data" and the selected state from the drop down list goes into the 3rd table "tab", "tab" consists of 2 columns ID and stat where the state name gets stored here. I joined the above two tables "data" and "tab" using inner join of SQL. When I fetched the data in another web page, the name, email id, contact and address are getting printed but not the the statename. Instead of the state name, ID of the statename (as given in table cool) is getting printed.
I want state name to get printed.
Here is the drop down list created using the data from my database :
<td>State :</td>
<td>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'colleges');
$resultset = $mysqli->query("SELECT ID, Statename from cool");
?>
<select name="state">
<?php
while($rows = $resultset->fetch_assoc())
{
$ID = $rows['ID'];
$Statename = $rows['Statename'];
echo "<option value='$ID'>$Statename</option>";
}
?>
</select>
</td>
</tr>
And what are the changes to be done here to insert the selected dropdown state name into the table in my database ?
<?php
$connection = mysqli_connect("localhost", "root", "", "colleges");
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$state = $_POST['state'];
if($name !=''||$email !=''){
//Insert Query of SQL
$insert = "INSERT Into data(student_name, student_email, student_contact, student_address) values ('$name', '$email', '$contact', '$address')";
$query = mysqli_query($connection, $insert);
$insert2 = "INSERT Into tab(stat) values ('$state')";
$query2 = mysqli_query($connection, $insert2);
echo "<br/><br/><span>Data has been inserted successfully</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank</p>";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
3). The printing part:
<?php
$hostname = "localhost";
$dbname = "colleges";
$username = "root";
$password = "";
$conn = mysqli_connect("$hostname","$username","","$dbname");
if(mysqli_connect_errno())
{
echo "Failed to Connect MySQL (phpmyadmin) Database: ".mysqli_connect_error();
}
$query = ("select student_name, student_email, student_contact, student_address, stat from data t2 inner join tab t3 on t2.ID=t3.ID");
$result = mysqli_query($conn, $query);
echo "<center>";
echo "<h1>Student list</h1>";
echo "<hr/>";
echo"<table border = '1'>
<tr>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>State</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['student_name']."</td>";
echo "<td>".$row['student_email']."</td>";
echo "<td>".$row['student_contact']."</td>";
echo "<td>".$row['student_address']."</td>";
echo "<td>".$row['stat']."</td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
mysqli_close($conn);
?>
echo "<option value='$ID'>$Statename</option>";
and
$state = $_POST['state'];
and
$insert2 = "INSERT Into tab(stat) values ('$state')";
You are actually not inserting the name of the state, but it's id, as the select return the selected option's value, not it's content. You can either change the first line to
echo "<option value='$Statename'>$Statename</option>";
which is a weird solution, or just use a join in your mysql query to get the statename
JOIN ON cool.ID = tab.stat
Extention:
When you use select, the innerHTML of option is displayed, but the value is sent in POST. So if you write
<select name="state">
<option value="1">name</option>
</select>
You will see name name, but the 1 will be sent.
On the next page, $State = $_POST['state']; will have $State the value of '1'. In the SQL you put this value to your stat field in your database, with a generated ID. It means, your ID won't hold any data, but the state field will!
So when printing on the third page, you have to join the list of states by it's ID with the stored stateid in the 'state' field. Then you will be able to print the statenames.
"SELECT * FROM t2 LEFT JOIN t3 ON t2.?? = t3.?? LEFT JOIN t1 ON t1.ID = t3.state"
Or something similar. Do you have a field you can use to join the t2 and t3 tables? It seems you are losing data when inserting to your database.

Inserting value in table with the click of a button

I'm working on a file called test.php.
What I'm trying to do is, to insert a value into a table by clicking a submit button
I have two tables, tbl_1 and tbl_2
tbl_1
id | name | age
4 | john | 20
9 | tim | 25
8 | lea | 22
While tbl_2 have the same structure as tbl_1, it is empty or without any value in it... the idea is that I want to have a button, after clicking on that button, it will insert the value of tbl_1 into tbl_2 based on the id
The question is, how do I fill in tbl_2 with the value of tbl_1, through a click of a submit button?
I made a form, trying to bring the value from tbl_1 to tbl_2, but to no avail...
<form action="test.php?id" method="post">
<input type="submit" class="btn btn-info btn-xs" name="submit" value="Copy"/>
</form>
<?php
if(isset($_POST['submit']))
{
$io = $_POST['io'];
$no_kes = $_POST['no_kes'];
$SQL = "INSERT INTO tbl_2(name, age) VALUES ( '".$name."', '".$age."')";
$result = mysql_query($SQL);
}
?>
Below is how my table looks like on the web.
Below is the code for the table I constructed.
<table class="table table-striped table-bordered">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
<?php
// Read
$per_page = 7;
if (isset($_GET["page"]))
$page = $_GET["page"];
else
$page = 1;
$start_from = ($page-1) * $per_page;
$sql = "select * from tbl_1";
$result = $mydb->query($sql);
while ($readrow = $result->fetch_array()) {
?>
<tr>
<td><?php echo $readrow['id']; ?></td>
<td><?php echo $readrow['name']; ?></td>
<td><?php echo $readrow['age']; ?></td>
<td>
There are couple of things you need to change in your code, such as:
You need to change your form's action attribute in the following way,
<form action="test.php?id=<?php echo $readrow['id']; ?>" method="post">
<input type="submit" class="btn btn-info btn-xs" name="submit" value="Copy"/>
</form>
Subsequently, you have to catch a particular row's id in test.php page the following way,
$id = (int)$_GET['id'];
Finally perform your INSERT operation in the following way,
if(isset($_POST['submit'])){
$id = (int)$_GET['id'];
$SQL = "INSERT INTO tbl_2(name, age) SELECT name, age FROM tbl_1 WHERE id = {$id}";
$result = mysql_query($SQL);
}
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
Since you already mentioned tbl_2 has the same structure as tbl_1, you may simply construct your DB query as:
insert into tbl_2(id, name, age) select tbl_1.id, tbl_1.name, tbl_1.age from tbl_1 left join tbl_2 on tbl_1.id = tbl_2.id;
What this does:
It scans tbl_1 and inserts any values that are missing in
tbl_2 table. It has the potential to insert duplicate values. For
that, you should have enough robust DB structure that avoids
duplicate values in a table (using unique keys etc).

How can i highlight (color) specific row in php from color in mysql database?

Tables
So i have 2 tables:
1st has id, username, lastname, title
2nd has id, title, color
and i can create entries in those tables.
The problem
what i need to do is if i submit a form like this into 2nd table: Admin, blue; and a form like this in the first table: someuser, lastname, Admin i get the whole row in displayed table colored blue,
similarly if i enter Guest, red; and anotheruser, lastname, Guest i get the whole row red and so on..
so far i can only make the 2nd table to have different colored rows:
What i have so far
<?php
$q = "SELECT *";
$q .= "FROM tbl1";
$r = mysql_query($q,$connection);
while($rows = mysql_fetch_assoc($r))
{
?>
<?php
$q = "SELECT *";
$q .= "FROM tb2";
$r = mysql_query($q,$connection);
while($row = mysql_fetch_assoc($r))
{
?>
The second table is used only for color
<tr style="background-color: <?php echo $row['color'];?>">
<td>some data from table 1</td>
</tr
<?php }}?>
You are missing your closing tr tag.
<?php
$q = "SELECT *";
$q .= "FROM tbl";
$r = mysql_query($q,$connection);
while($row = mysql_fetch_assoc($r))
{
?>
<tr style="background-color: <?php echo $row['color'];?>">
<td>somedata</td>
</tr>
<?php }?>

Displaying user's SQL query using PHP

Please can anyone help me with this?
I have 2 tables, location and tickets and what I have built so far is a form in a div that users enter the name of the city or town where they would like to see a live music performance. This form is submitted and an SQL statement is passed querying the location table. In another div, the users search query appears in a box on the screen. What I would like to do next is to write an SQL statement that will lookup the user's query and dynamically display the relevant ticket information from the ticket table based on the location ID.
For example, the user types in 'Newcastle' as their search query, the location table finds the city of Newcastle and displays the user's result in a div called 'tickets'..I would like to display all the fields that correspond with 'Newcastle' from the ticket table.
The locationID is the primary key in the location table and has 3 other column, city, town and postcode.
The ticket table consists of ticketID being the primary key, the locationID being the foreign Key and the other fields i.e venue, tPrice, date and time. I think the problem im having is im not passing through the variable from the users query so that the ticket table can look it up and display the relevant information.
Here is the code for the form:
<div id="search">
<form name="searchForm" id="searchForm" class="searchForm" method="post">
<input type="text" name="citySearch" id="citySearch" class="citySearch" placeholder="Enter name city/town..." autofocus="autofocus" />
<input type="submit" name="ticketSearch" id="ticketSearch" class="ticketSearch" value="Search" />
</form>
</div>
Here is the code to display the user's query:
<div id="locationResult">
<?php
include( 'classes/database_connection.php' );
$cSearch = $_POST['citySearch'];
$sql = "SELECT DISTINCT city FROM location WHERE city = '$cSearch'";
mysql_query($sql) or die (mysql_error());
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$city = $row['city'];
echo $row["city"];
}
mysql_free_result($queryresult);
mysql_free_result($qResult);
mysql_close($conn);
?>
</div>
</div>
This is where I want to display the ticket results from the ticket table:
<div id="ticketsResults">
<table class="ticketResult" border="0" cellspacing="5">
<tr>
<td><b>Venue</b></td>
<td><b>Price</b></td>
<td><b>Date</b></td>
<td><b>Time</b></td>
<td><b>Street View</b></td>
</tr>
<?php
include( 'classes/database_connection.php' );
$locID = $_POST['locationID'];
$citySearch = $_POST['citySearch'];
$sQL = "SELECT locationID FROM location";
//Here is where I want it to display dynamic information rather than manually type the location
$ticketSQL = "SELECT * FROM ticket NATURAL JOIN location WHERE city = 'Newcastle' ";
mysql_query($sQL) or die (mysql_error());
$qResult = mysql_query($sQL) or die(mysql_error());
mysql_query($ticketSQL) or die (mysql_error());
$result = mysql_query($ticketSQL) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// $ticketID = $row['ticketID'];
$venue = $row['venue'];
$ticketPrice = $row['tPrice'];
$date = $row['date'];
$time= $row['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>&pound$ticketPrice</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td>Click to see</td>\n";
echo "</tr>\n";
}
mysql_free_result($qResult);
mysql_free_result($result);
mysql_close($conn);
?>
</table>
</div>
So basically, I'm wanting an SQL statement that dynamically displays the tickets according to the user's query. Sorry about the copious amount of code! Any help given is greatly appreciated.
Before you do anything else I think you should work on your coding style, specifically your indentation. A quick google search should do the trick. Next look into mysql prepared statements because currently your code is unsafe. Like jordanm said, it is subject to SQL injection.
For example, if someone entered blah' OR 'x'='x as a city name. Your query would become
SELECT DISTINCT city FROM location WHERE city = 'blah' OR 'x'='x';
Basically it allows the user to do naughty things with your query, and you don't want that.
Below is a sample of how you can avoid this using mysql prepared statements:
// basic quick raw example
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT DISTINCT city FROM location WHERE city = ?');
$stmt->bind_param('s',$city_name);
$stmt->execute();
$stmt->bind_result($city);
while ($stmt->fetch())
{
echo $city;
}
That's all I'm going to leave you with because I feel like to answer the actual question (?) I will need to write the code for you. Goodluck

Categories