Hi everyone im new at php so here is my code i am having trouble displaying php in many to many relationship im doing a student information system
here is my database
student
student_id
name
address
course
subject
subject_id
subject_name
subject_code
student_subject
subject_id
student_id
Here is my query
$sql = "SELECT subject_name
FROM subject
LEFT JOIN student_subject ON (student.student_id = 'student_id')
LEFT JOIN subject ON (subject.subject_id = 'subject_id' )";
$records = mysql_query($sql);
and now this is my code to display it please help me how to display this example i just only want to display the subject name and the subject code
while($student=mysql_fetch_array($records)){
echo $student['subject_name'];
echo $student['subject_code'];
}
this is only sample because this is only what i want to dispaly please help me thanks sorry for my bad english. cant search anything about displaying many to many relationship in google i can see some query but i cant search about the code i tried many but i always failed thank you so much
desired Output:
Subject Name ---|--- Subject CODE
ICT___________||_________IT 101
ALGEBRA_______||_________ MATH101
remove the underscore in your vision cant fix the output new here in stackoverflow
<?php
$con = mysql_connect("localhost", "root", "") or die('There is an error to connect DB' . mysql_error());
mysql_select_db('test') or die ('Unable to select DB' . mysql_error());
$query = 'SELECT ST.student_id, ST.name, ST.address, SB.subject_name, SB.subject_code FROM student ST, subject SB, `student_subject` STSB WHERE STSB.student_id=ST.student_id AND STSB.subject_id=SB.subject_id';
$query = mysql_query($query) or die('Unable to execute query' . mysql_error());
if ($query) {
$str = '';
$header = '<tr><td>Student ID</td><td>Name</td><td>Address</td><td>Subject</td><td>Subject Code</td></tr>';
while ($row = mysql_fetch_array($query)) {
$str .= '<tr>';
$student_id = $row['student_id'];
$name = $row['name'];
$address = $row['address'];
$subject = $row['subject_name'];
$subject_code = $row['subject_code'];
$str .= '<td>' . $student_id . '</td>';
$str .= '<td>' . $name . '</td>';
$str .= '<td>' . $address . '</td>';
$str .= '<td>' . $subject . '</td>';
$str .= '<td>' . $subject_code . '</td>';
$str .= '</tr>';
}
if ($str) {
$table = '<table border="1">' . $header . $str . '</table>';
} else {
$tdata = '<tr><td colspan="5">No data found</td></tr>';
$table = '<table border="1">' . $header . $tdata . '</table>';
}
echo $table;
}
Output will be like this:
Related
I want to write an php function that will echo sql query results in a specific manner.
Example I have table 1 which is 10.000 rows * 43 columns:
NO NAME Prof Date of birth
1 John Teacher 1987
2 Nick Engineer 1976
3
4
5
And so on. Based on No which is an integer (1-10.000), I want to generate tables such as:
Name: John
Prof: Teacher
Date of birth: 1987
Name: Nick
Prof: Engineer
Date of birth: 1976
So far my code:
`
$hostname = "";
$username = "";
$password = "";
$dbname = "db1";
//connection to the database
$con = mysqli_connect($hostname, $username, $password, $dbname)
or die("Unable to connect to MySQL");
mysqli_set_charset($con, 'utf8');
/*echo "Connected to db1 database <br>";
else
echo "Could not connect"; */
$query1 = "SELECT * FROM `table 1` WHERE CODE_NO = 1";
$query2 = "SHOW COLUMNS FROM table 1";
$result1 = mysqli_query($con, $query1);
$result2 = mysqli_query($con, $query2);
// Check result
// Useful for debugging.
if (!$result1) {
$message = 'Invalid query: ' . mysqli_error($con) . "\n";
$message .= 'Whole query: ' . $query1;
die($message);
}
echo "<table>"; // table tag in the HTML
while($row = mysqli_fetch_array($result1))
//Creates a loop to loop through results
{
echo
"<tr>
<th>CODE_NO:</th>
<td>" . $row['CODE_NO'] . "</td>
</tr>
<tr>
<th>FIRST_NAME:</th>
<td>" . $row['FIRST_NAME'] . "</td>
</tr>
<tr>
<th>SURNAME:</th>
<td>" . $row['SURNAME'] . "</td>
</tr>
<tr>
<th>Date of birth:</th>
<td>" . $row['DOB'] . "</td>
</tr>
<tr>
<th>Date of death:</th>
<td> " . $row['DOD'] . "</td>
</tr>";
}
echo "</table>"; //Close the table in HTML
?>`
Is it possbile to code the process once, without hard-coding anything, so it could be repeated as many times as needed?
Edit:
$x = 1;
$query = "SELECT * FROMpersonsWHERE CODE_NO = '$x'";
$result = mysqli_query($con, $query);
If I understood you correctly, this would do what you need:
function generateTableFromResult($result) {
$html = "<table>";
while($row = mysqli_fetch_array($result)) {
foreach($row as $column => $value) {
$html.="<tr><th>".$column."</th><td>".$value."</td></tr>";
}
}
$html.="</table>";
return $html;
}
// usage:
// ...
$result1 = mysqli_query($con, $query1);
echo generateTableFromResult($result1);
You can have the excepted result.
You will need to have a variable to be incremented with the values and returned at the end.
See my example:
// Check result
// Useful for debugging.
if (!$result1) {
$message = 'Invalid query: ' . mysqli_error($con) . "\n";
$message .= 'Whole query: ' . $query1;
die($message);
}
$table = "<table>"; // table tag in the HTML
while($row = mysqli_fetch_array($result1)){
//Creates a loop to loop through results
$table .="<tr>";
$table .=" <th>CODE_NO:</th>";
$table .=" <td>" . $row['CODE_NO'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>FIRST_NAME:</th>";
$table .=" <td>" . $row['FIRST_NAME'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>SURNAME:</th>";
$table .=" <td>" . $row['SURNAME'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>Date of birth:</th>";
$table .=" <td>" . $row['DOB'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>Date of death:</th>";
$table .=" <td> " . $row['DOD'] . "</td>";
$table .="</tr>";
}
$table .= "</table>"; //Close the table in HTML
echo $table;
?>`
This is a possible approach to get the result that you want.
However you sent an array in the json format with the values and in the front end build the table using js.
Revised function generateTableFromResult from above that works correctly
function generateTableFromResult($result) {
$html = "";
$i = 0;
$header = "<tr>";
$body = "";
while($row = mysqli_fetch_assoc($result)) {
$i += 1;
$body .= "<tr>\n";
foreach($row as $column => $value) {
if ($i == 1){
$header .= "<th>$column</th>\n";
}
$body .= "<td>$value</td>\n";
}
$body .= "</tr>\n";
}
$header .= "</tr>\n";
$html .= "<table> $header $body</table>";
return $html;
}
I'm trying to design a webpage where it simply shows info from a database using PHP.
I almost solve all of my problem but it's the first time I'm using HTML and I am having trouble finding a solution for my problem.
The code I have so far is:
<?php
$connection = mysql_connect('localhost','XXXX','XXXX');
mysql_select_db('cardata_laptimer');
echo "<table>";
echo "<table border = 1>";
$query = "SELECT * from tempos GROUP BY piloto";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$query = "SELECT * from tempos WHERE piloto = '" . $row['piloto'] . "' ORDER BY tempo";
$resultado = mysql_query($query);
echo "<td>" . $row['piloto'] . "</td></tr>";
while($rows = mysql_fetch_array($resultado))
{
echo "<td>" . $rows['tempo'] . "</td><td>" . $rows['data'] . "</td></tr>";
}
}
The output I'm getting can be seen in www.cardata.pt
1st problem: How to I make the "piloto" (for example AA) occupy the space of 2 cells?
2nd problem: I want the table to show "pilotos" side by side and the info for each one (tempo and data) down the piloto name.
Thanks in advance
To occupy the space of 2 cells add : colspan="2"
here is my edit of your code :
<?php
$connection = mysql_connect('localhost','XXXX','XXXX');
mysql_select_db('cardata_laptimer');
echo '<table border="0"><tr>';
$query = "SELECT * from tempos GROUP BY piloto";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo '<td><table border="1"><tr>';
$query = "SELECT * from tempos WHERE piloto = '" . $row['piloto'] . "' ORDER BY tempo";
$resultado = mysql_query($query);
echo '<td colspan="2">' . $row['piloto'] . "</td></tr><tr>";
while($rows = mysql_fetch_array($resultado))
{
echo "<td>" . $rows['tempo'] . "</td><td>" . $rows['data'] . "</td>";
}
echo '</tr></table></td>';
}
echo '</tr></table>';
?>
New to PHP, first post on stackoverflow... From the tutorials I've read, I'm 'somewhat' protected from injection, and I know I'm passing my variables correctly from my search form. The issue I'm having is when I attempt to read the results; I receive an "undefined index" error for them and I have no idea why. I've been staring at this and reading for the last day and am about to pull out my hair. Would someone be able to point me in the right direction? and yes, i know, don't use root; this is purely for demo and hosted locally until i have everything smoothed out. Thanks for any help! -Jason
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("%[a-zA-Z0-9_-]%", $_POST["booktext"])){
$searchvalue=$_POST["booktext"];
// create connection
$user="root";
$password="";
$database="bookcat_data";
$host="127.0.0.1:3306";
$searchtype=$_POST["searchtype"];
$con=mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT Book.BookID, Book.Title, Book.AuthorSort, Publisher.Publisher, Book.PublishDate, Book.ISBN FROM ((Book LEFT JOIN Edition ON Book.EditionID = Edition.EditionID) LEFT JOIN PrintedBy ON Book.PrintedByID = PrintedBy.PrintedByID) LEFT JOIN Publisher ON Book.PublisherID = Publisher.PublisherID WHERE " . $searchtype . " LIKE '%" . $searchvalue . "%' ORDER BY Book.Title;";
$result=mysqli_query($con,$sql);
switch($searchtype) {
case "Book.Title":
$header="Book Title";
break;
case "Book.AuthorSort":
$header="Author";
break;
}
echo '<title>' . $header . ' Search for "' . $searchvalue . '"</title>';
echo '<h3 align="center">' . $header . ' Search for "' . $searchvalue . '" - Sorted by Title</h3>';
echo '<table cellpadding="3" cellspacing="2" border="1" id="catalogs" class="center">';
echo '<tr><th>Book Title</th><th>Author</th><th>Publisher</th><th>Publish Date</th><th>ISBN</th>';
while($row=mysqli_fetch_array($result)) {
$BookID=$row['Book.BookID'];
$BookTitle=$row['Book.Title'];
$Author=$row['Book.AuthorSort'];
$Publisher=$row['Publisher.Publisher'];
$PublishDate=$row['Book.PublishDate'];
$ISBN=$row['Book.ISBN'];
echo '<tr>';
echo '<td><a href=\'bookinfo.php?id=$BookID\'>' . $BookTitle . '</td>';
echo '<td>' . $Author . '</td>';
echo '<td>' . $Publisher . '</td>';
echo '<td>' . $PublishDate . '</td>';
echo '<td>' . $ISBN . '</td>';
echo '</tr>';
}
echo '</table>';
mysqli_free_result($result);
mysqli_close($con);
}
}
else{
echo "<p>Please enter an appropriate search</p>";
}
}
SQL queries return the column names without the table prefix. Remove this prefix when accessing your array elements. So $row['BookID'] instead of $row['Book.BookID'].
I can't put a table around my results from my code and need some help as I've tried but it comes back with "Parse error: syntax error, unexpected '<' in C:\xampp\htdocs\search_go.php on line 27". So could I get help with how to insert a table?
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['keyname']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = "localhost"; //server
$db = "calendar"; //database name
$user = "root"; //dabases user name
$pwd = ""; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT * FROM caltbl WHERE evtDate LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
<table>
/* check whether there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
<tr>
$output .= "date: " . $row['evtDate'] . "<br />";
$output .= "Name: " . $row['patient'] . "<br />";
$output .= "Course: " . $row['patientId'] . "<br />";
}
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
?>
You can't just insert a HTML tag inside PHP code:
You can however just use an echo to send it out directly:
echo "<table>";
while($row = mysqli_fetch_array($results))
{
$output = "<tr>";
// <tr> This is the problem line.
$output .= "<tr>";
$output .= "<td>date: " . $row['evtDate'] . "<br /></td>";
$output .= "<td>Name: " . $row['patient'] . "<br /></td>";
$output .= "<td>Course: " . $row['patientId'] . "<br /></td>";
$output .= "</tr>";
echo $output;
}
Additionally you didn't close your <tr>. I added some extra snippets to make each field a TD in the table and then closed the row.
I am working on a basic messaging system. This is to get all the messages and to make the row of the table that has an unread message Green. In the table, there is a column called 'msgread'. this is set to '0' by default. Therefore it should make any row with the msgread = 0 -> green. this is only working for the first row of the table with the code i have - i verified that it is always getting a 0 value, however it only works the first time through in the while statement ..
require('./connect.php');
$getmessages = "SELECT * FROM messages WHERE toperson = '" . $userid . "'";
echo $getmessages;
$messages = mysql_query($getmessages);
if(mysql_num_rows($messages) != 0) {
$table = "<table><tr><th>From</th><th>Subject</th><th>Message</th></tr>";
while($results = mysql_fetch_array($messages)) {
if(strlen($results[message]) < 30){
$message = $results[message];
}
else {
$message = substr($results[message], 0 ,30) . "...";
}
if($results[msgread] == 0){
$table .= "<tr style='background:#9CFFB6'>";
$table .= "<td>" . $results[from] . "</td><td>" . $results[subject] . "</td><td><a href='viewmessage.php?id=" . $results[message_id] ."'>" . $message . "</a></td></tr>";
}
else {
$table .= "<tr>";
$table .= "<td>" . $results[from] . "</td><td>" . $results[subject] . "</td><td><a href='viewmessage.php?id=" . $results[message_id] ."'>" . $message . "</a></td></tr>";
}
}
echo $table ."</table>";
}
else {
echo "No Messages Found";
}
There's all the code, including grabbing the info from the database. Thanks.
if(strlen($results[message]) < 30){
the message probably should be quoted:
if(strlen($results['message']) < 30){
There are quite a few other similar issues
i tested your code an the only mistake i found was the lack of quoatation marks in the indices array $results. You are using this $result[message_id] when the most appropriate would be $result['message_id']. The rest works as expected, the records with msgread equal to 0 stayed with the green line.
Your code looks a little nasty and is not easy to read.
You should use mysqli_fetch_assoc().
Always end style with a ;
use quotation on associative array
more logic choice of var names
where does $userid come from? is the content safe?
Here is quickly cleaned version of your code :
$query = "SELECT * FROM messages WHERE toperson = '" . $userid . "'";
if($results = mysqli_query($query)) {
if(mysqli_num_rows($results) != 0) {
$table = "<table><tr><th>From</th><th>Subject</th><th>Message</th></tr>";
while($data = mysqli_fetch_assoc($results)) {
if(strlen($data['message']) > 30){
$data['message'] = substr($data['message'], 0 ,30) . "...";
}
$table .= "<tr";
if($data['msgread'] == 0){
$table .= " style='background:#9CFFB6;'";
}
$table .= ">";
$table .= "<td>" . $data['from'] . "</td><td>" . $data['subject'] . "</td><td><a href='viewmessage.php?id=" . $data['message_id'] ."'>" . $data['message'] . "</a></td></tr>";
}
echo $table ."</table>";
} else {
echo "No Messages Found";
}
}