Handling loops and combining values in PHP - php

I have a table like this.
author_id author_state author_name
1 CA Hello
2 MI World
3 CA How
4 MI Are
Please let me know how can I achieve this. In other words, I should loop it and combine the state values first and display the details.
Here is my PHP Code
<table>
<tr><td>Author ID</td><td>Author State</td><td>Author Name</td></tr>
<?php
$row_data = mysql_query("select * from author" );
while($row = mysql_fetch_array($row_data) ) {
?>
<tr>
<td><?php echo $row['author_id']; ?></td>
<td><?php echo $row['author_state']; ?></td>
<td><?php echo $row['author_name']; ?></td>
</tr>
<?php } ?>
</table>
My Expected output is to combine the state and display something like below:
Author ID Author Name
=======================================
CA
==
1 Hello
3 How
MI
==
2 World
4 Are

You can do this fairly easily, by sorting your output by author_state, and using a variable to keep track of which state you're outputting. If the state changes, then you simply output the state as a new header.
You can take advantage of the SQL order by clause so that you don't have to sort the data yourself.
Here is an edit of your code, where I've simply added the order by to your mysql_query(), and added a variable for $current_state.
<table>
<tr><td>Author ID</td><td>Author State</td><td>Author Name</td></tr>
<?php
$current_state = "";
$row_data = mysql_query("select * from author order by author_state" );
while($row = mysql_fetch_array($row_data) ) {
// Output the "new" state
if ($row['author_state'] != $current_state)
{
echo "<tr><td colspan=\"3\">{$row['author_state'}}</td></tr>";
$current_state = $row['author_state'];
}
?>
<tr>
<td><?php echo $row['author_id']; ?></td>
<td><?php echo $row['author_state']; ?></td>
<td><?php echo $row['author_name']; ?></td>
</tr>
<?php } ?>
</table>
As a side note, I would strongly encourage you to look into using mysqli or PDO instead of the mysql_* functions. The mysql_* functions are only availble in very old versions of PHP (they were completely removed in PHP7).

Related

Using links in HTML tables associated with the right table row/person/id in the database

Im a begginer in the whole SO and programming enviroment, and here comes my first question(which i tried finding in here but with no luck so far..)
I have an html table that prints specific patients of the doctor that is active (in a simple web-application that i created). The doctor gets filtered using $_SESSIONS global var in php.
My problem is that i want to implement a few actions in the same HTML table that displays the patients, like view history (which is stored in a local DB table, from an HTML from using POST method) and create a new form for the same person.
I saw that providing the table with row.ids could be a solution, but my table isn't static, i woulda like for the user to have the option to add/delete patients..
Following is a sample of my code that displays the HTML table "Existing Patients" :
<table>
<tr>
<th>Patient Id</th><th>Patient Name</th><th>Phone Number</th><th>Email</th><th>History</th>
<th>Add a Follow Up Visit</th><th>Remove Patient</th>
</tr>
<?php $sql = "SELECT * FROM patients WHERE Doctor_ID = $usersid";
$result = $pdo->query($sql);
if($result->rowCount() > 0){
while($row = $result->fetch()){?>
<tr>
<td><?php echo $row['Patient_id']; ?></td>
<td><?php echo $row['Patient_name'] ; ?></td>
<td><?php echo $row['Phonenum'] ; ?></td>
<td><?php echo $row['Email']; ?></td>
<td><?php echo "<a href='/patienthistory.php'</a>" . 'Previous Visits'; ?></td> //problem here
<td><?php echo "<a href='/patientform.html'</a>" . 'Add Follow Up' ; }?></td> //and here
</tr>
</table>
I want the last 2 lines to connect immediately to the specific database stored Patient_id and retrieve the existing information stored there from the patients previous visits.
I hope i gave enough of a description, but if there is any more info neccesary, please let me know.
Thank you in advance!
You can specify the patient ID as a query parameter in the URL that you're linking to. Also the HTML you're generating for your links is invalid currently. And the second link is going to need to go to a .php script, not a .html file, if you want it to execute code and fetch data.
Try this example:
<td><?php echo "<a href='/patienthistory.php?id='".$row['Patient_id']."'>Previous Visits</a>"; ?></td>
<td><?php echo "<a href='/patientform.php?id='".$row['Patient_id']."'>Add Follow up</a>"; ?></td>
Then in each of the PHP scripts, use $_GET["id"] to retrieve that ID of the patient and use that in a query
e.g.
$patientID = $_GET["id"];

Use PHP to get SQL data for various IDs

I currently have a table on my website which I have in my SQL database and I need each row of my table to get certain information from the columns. I have something that works just fine at the moment, however, I have a feeling its not the best way of doing things. As I have around 600+ rows in my database.
I'm trying to learn more about all of this so if you have any idea to do this in a better way then that would be fantastic.
<?php
$queryContent="SELECT * FROM businesses WHERE id= 104";
$resultContent= $mysqli->query($queryContent);
$rowContent = $resultContent->fetch_assoc();
?>
<?php if ($rowContent['active'] == "Y") { ?>
<tr>
<td><?php echo $rowContent['businessname']; ?></td>
<td><?php echo $rowContent['telephoneno']; ?></td>
<td><?php echo $rowContent['emailaddress']; ?></td>
<td><?php echo $rowContent['rating']; ?></td>
</tr>
<?php } ?>
If you are trying to list all active rows, try something like this:
<?php
// Change query to select only acitve rows
$queryContent="SELECT * FROM businesses WHERE active = 'Y'";
$resultContent= $mysqli->query($queryContent);
//while cycle will repeat while sql have results
while($rowContent = $resultContent->fetch_assoc()){
?>
<tr>
<td><?php echo $rowContent['businessname']; ?></td>
<td><?php echo $rowContent['telephoneno']; ?></td>
<td><?php echo $rowContent['emailaddress']; ?></td>
<td><?php echo $rowContent['rating']; ?></td>
</tr><?php } ?>
Php documentation examples should be also usefull.
When you have a list of IDs wich you want to select from sql look at SQL WHERE - IN operator and syntax.
SELECT * FROM businesses WHERE id IN (103, 104, 105)
I could think of two things which can be improved in your code:
instead of select *, you can mention select column1, column2,... which is considered to be the standard
And if you are trying to list only one row, then either access the $rowcontent array with index 0 (or) limit the select query's output rows by using "LIMIT 1" at the end of "SELECT" query (second option valid only if you are not sure about the query whether it will fetch only one row always or not)

Trouble with displaying the result of a select in a table

So, I have an sql table that doesn't have a unique column. I have to display it in a table by it's ID. But, like I said, the ID is not unique
OBSĀ¹: Notice that it comes from a select statement
OBSĀ²: the user id can appear in the select from 0 up to 4 times (according to id_questionario)
So, the thing is, how am I going to make a table that will show only one time user_id but will display by it's side all the melhor_tentativa according to id_questionario (notice that id_questionario is not to be displayed, only so I can display the melhor_tentativa in the correct order)
What I understand is that I have lines that should be columns. I've been trying for 2 days to figure this out and turns out I can't. Thought that it might be miss in how I made my sql
This is how the table looks
This is how the sql table looks
And bellow is the code I made for it
<?php
$count = 0;
$nota1 = 0;
$nota2 = 0;
$nota3 = 0;
$nota4 = 0;
?>
<?php
foreach($notas as $nota):
$total = 0;
?>
<tr>
<td><?php echo $nota['user_id']?></td>
<td>NULL</td>
<?php
if($nota['id_questionario']==1){
$nota1 = $nota['melhor_tentativa']*20;
}
?>
<td><?php echo $nota1 ?></td>
<?php
if($nota['id_questionario']==2){
$nota2 = $nota['melhor_tentativa']*20;
}
?>
<td><?php echo $nota2 ?></td>
<?php
if($nota['id_questionario']==3){
$nota3 = $nota['melhor_tentativa']*20;
}
?>
<td><?php echo $nota3 ?></td>
<?php
if($nota['id_questionario']==4){
$nota4 = $nota['melhor_tentativa']*20;
}
?>
<td><?php echo $nota4 ?></td>
<td><?php $total = ($nota1 + $nota2 + $nota3 + $nota4)/4; echo $total; ?></td>
</tr>
<?php $count++; ?>
<?php
endforeach;
echo $count;
?>
</table>
P.S: I know that total is completly wrong ;)
After a bunch of work I figured this out. So what I did was the following. I had that table which would show 4 results for a one ID. I made a view out of this table
Then I did a subquery from that view, so I would be able to show all results in one line
Hope it helps anybody in the future :)

Shows only the first letter of a sentence/word when echoed in php

I'm trying to display the date from the database using the following code.
<?php
$query_course = mysqli_query($databaseConnection,"SELECT * FROM grading WHERE courseid=".$courseid);
$count=0;
while($row = mysqli_fetch_array($query_course))
{
$gradename[$count]= $row['gradingname'];
$percentage[$count]= $row['percentage'];
$date[$count]= $row['date'];
?>
<tr>
<td><?php echo $gradename[$count]; ?></td>
<td><?php echo $percentage[$count]; ?></td>
<td><?php echo $date[$count]; ?></td>
</tr>
<?php $count++;
} ?>
But it displays only the first letter/digit for the date. Database looks fine. What might be the problem?
The only thing that would explain this is if $gradename etc. were initialised as strings. E.g.:
$foo = '';
$foo[0] = 'bar';
echo $foo[0]; // b
Make sure you initialise your variables as arrays before the loop:
$gradename = array();
...
(I'd question the usefulness of those extra arrays to begin with, but that's outside the scope of this question.)
it displays the first digit because you use the count as index. Since the count is 0 it display just the first digit from date. Remove the $count and echo the $row['date'].

running sql on link click

please view the following code.
<?php foreach($rows as $row): ?>
<tr>
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo htmlentities($row['id'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo htmlentities($row['starthol'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlentities($row['endhol'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlentities($row['days'], ENT_QUOTES, 'UTF-8'); ?></td>
<td>Approve</td>
<td>Reject</td>
</tr>
This populate a table from a previously ran sql query. Basically, when approve is clicked,I want to run an SQL query that uses the id of the the row and updates a column in the table called "active".
UPDATE holidays
SET active = "active"
WHERE holid = getid
Any advice on how to do this?
I am a php novice, so please go easy on me. Thank you.
You should consider learning how to GET and POST
<td><a href="active.php?id=?"<?php echo $row['id']; ?> >Approve</a></td>
Server side code active.php(sample dont copy paste you must use post to update db state not get also mysql_* depricated)
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE holidays
SET active = 'active'
WHERE holid = $id")or die(mysql_error());
header('location:listingpage.php?msg=approved');
Are you able to get your query to run and return data? Assuming you have data, you will want to update your foreach() loop. If you want the loop to work over more than one line, you'll have to use curly braces ({ })
So your code would look more like:
<?php foreach($rows as $row) { ?>
...
<?php } ?>

Categories