Results of MYSQL query printed twice using PDO - php

I am a teacher and I have a mysql table called 'gabber' which holds scores of student quizzes. The fields are 'Exercise', 'realname, 'Score', 'Start_Time' and 'End_Time'. If a student completes more than one type of quiz, then this will appear as another row in the table, but of course with a different Exercise value.
My code below, which very nearly works, first finds the unique exercise values, and uses these to print the table column headings. These unique exercise values are also used to create the second query, which finds the minimum (i.e. first attempt) score for each student's attempt at each quiz.
Anyway, the php code works EXCEPT for printing each value twice. i.e. the name is printed twice, as is each score. I know that my query is definitely correct (tested in phpmyadmin), but I think things are going wrong in the nested for loop. I have tried reading about PDOstatement which the query returns, but I could not understand it. I appreciate that there are other posts on stackoverflower about "printing twice", but they could not help me solve this.
Any suggestions on how to make this work would be excellent. Thanks, Matt.
<?
$dbh = new PDO("mysql:host=XXX;dbname=gabber", user, pass);
$query2 = "SELECT realname";
echo '<style>table{border-collapse:collapse;}';
echo 'table, td, th{border:1px solid black;}</style>';
echo '<table><tr><td></td>';
foreach($dbh->query('SELECT DISTINCT Exercise FROM a2_physics') as $row) {
echo '<td>';
echo $row[0];
echo '</td>';
$query2.=', MIN( IF( Exercise = "';
$query2.=$row[0];
$query2.='", Score, NULL ) ) AS "';
$query2.=$row[0];
$query2.='"';
}
echo '</tr>';
$query2=$query2.' FROM a2_physics';
$query2=$query2.' GROUP BY realname';
//echo $query2;
foreach($dbh->query($query2) as $row) {
echo '<tr>';
foreach($row as $element)
{
echo '<td>';
echo $element;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>

When connecting to PDO, do it this way
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);

Related

How can I group values from a database using <td> and rowspan?

So, I am reading some values from a database. Such as 'result', 'team', 'league' from a database. I am trying to display, in a <table>, results of the specific team grouped by league, something like this:
That is assuming my database contains the following data:
result1 team1 league1
result2 team1 league1
result100 team1 league2
result101 team1 league2
result88 team1 league2
I have tried a lot of stuff and yet I can't get it to work. Also, the league cell must have a rowspan equal to the number of results detected in the specific league. This can be done with mysql_num_rows, but I don't know exactly where to place it. So how can I get this table to work? Thanks a lot!
Groupng the output by league is a simple matter of doing a break-sort on the results of your query. Since your question doesn't
include your table schema, or any php code, I've made some assumptions about your table, and will leave opening the connection to
your DB, and executing the sql statement to you.
$qstr = "SELECT league, team, event
FROM table
ORDER BY league, team, event";
// Execute query, get results into associative array $allrows
$league = "";
$col1 = "";
$col2 = "";
echo "<table>\n";
foreach($allrows as $rowno => $row) {
if($league != $row['league']) {
if($league != "") {
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
}
$league = $row['league'];
$col1 = $league;
$col2 = "";
}
$col2 .= $row['team']." got ".$row['event']."<br />\n";
}
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
echo "</table>\n";
I have try'd some way and it worked for me I hope it works for you...
Look at the code:
$db = new PDO('mysql:host=localhost;dbname=you_dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT league, result, team FROM matches_info';
$stmt = $db->query($sql);
echo "<table border=\"1\">";
while($row = $stmt->fetch()){
echo '<tr>
<td rowspan="3">'.$row['pcid'].'</td>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].' </td></tr>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].'</td></tr></tr>';
}
echo "</table>";
It is very basic you can Add more functions to improve the functionality of it.

PHP Getting Data From MySQL [duplicate]

I am a teacher and I have a mysql table called 'gabber' which holds scores of student quizzes. The fields are 'Exercise', 'realname, 'Score', 'Start_Time' and 'End_Time'. If a student completes more than one type of quiz, then this will appear as another row in the table, but of course with a different Exercise value.
My code below, which very nearly works, first finds the unique exercise values, and uses these to print the table column headings. These unique exercise values are also used to create the second query, which finds the minimum (i.e. first attempt) score for each student's attempt at each quiz.
Anyway, the php code works EXCEPT for printing each value twice. i.e. the name is printed twice, as is each score. I know that my query is definitely correct (tested in phpmyadmin), but I think things are going wrong in the nested for loop. I have tried reading about PDOstatement which the query returns, but I could not understand it. I appreciate that there are other posts on stackoverflower about "printing twice", but they could not help me solve this.
Any suggestions on how to make this work would be excellent. Thanks, Matt.
<?
$dbh = new PDO("mysql:host=XXX;dbname=gabber", user, pass);
$query2 = "SELECT realname";
echo '<style>table{border-collapse:collapse;}';
echo 'table, td, th{border:1px solid black;}</style>';
echo '<table><tr><td></td>';
foreach($dbh->query('SELECT DISTINCT Exercise FROM a2_physics') as $row) {
echo '<td>';
echo $row[0];
echo '</td>';
$query2.=', MIN( IF( Exercise = "';
$query2.=$row[0];
$query2.='", Score, NULL ) ) AS "';
$query2.=$row[0];
$query2.='"';
}
echo '</tr>';
$query2=$query2.' FROM a2_physics';
$query2=$query2.' GROUP BY realname';
//echo $query2;
foreach($dbh->query($query2) as $row) {
echo '<tr>';
foreach($row as $element)
{
echo '<td>';
echo $element;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
When connecting to PDO, do it this way
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);

Print MySQL table in PHP without knowing the columns

Im currently making a private "list management" system in which I store SQL queries in the database. So that I can via the front-end create new "lists" (which basicly are sql queries), and view them.
I have made the front end so you can save queries into the database, and im at the point where I want PHP execute and print out the results of one of my queries. This happens when I select one of my stored "lists" on my frontend. So when I press one of the lists, it should execute the SQL query. So far, so good.
But how can I, via PHP, print a table (like the one you get out from phpMyAdmin when viewing the contents of a table) without knowing how many / what columns exists? I want the script to be dynamic, so I can view results of all kinds of SELECT queries (on different tables).
Any tips or pointers?
Rather than using deprecated libraries, use PDO instead.
$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
//it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename");
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
//check if there are actual rows!
$first_row = reset($rows); //Resets the internal pointer, return the first elem.
$header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
$table_body_rows = array();
foreach($rows as $row){
$table_body_rows[] = '<td>' .
implode('</td><td>', $row) .
'</td>';
}
$body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
$tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
//something went wrong
}
show tables is probably what you need
echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);
If you need to print a row with header (column names), you have to do it this way:
$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
$row=mysql_fetch_assoc($result);
echo "<table>";
echo "<tr>";
echo "<th>".join("</th><th>",array_keys($row))."</th>";
echo "</tr>";
while ($row)
{
echo "<tr>";
echo "<td>".join("</td><td>",$row)."</td>";
echo "</tr>";
$row=mysql_fetch_assoc($result);
}
echo "</table>";
}
This is just the basic concept. If your table has values which may contain HTML tags and other stuff, you'll need to apply htmlspecialchars() on all values of $row. This can be done with array_walk(). Furthermore you didn't mention what PHP version are you using and what MySQL API do you prefer. Some people suggested to use mysqli or PDO, that's up to you to rewrite the code according to your preferred API.

Oracle/PHP oci_fetch_all() issue

Pretty new to PHP using Oracle. I'm following examples online. I'm using this example 1 from the official site. My issue is, it displays all the records like I want, but it's missing the column/field names. Does anyone now how to alter this so that it includes the headers? (ex, my employee table would have... First Name, Last Name....) Thanks
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employee');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
echo "<tr>\n";
foreach ($col as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>
Most DBMS(I haven't worked with them all so I can't say "all") systems have a separate table that stores this sort of meta information, so you'd want to query it. In Oracle, it's stored as a dictionary, probably in some sort of table header data or meta info (I really don't know Oracle's underlying structure well) and it's called user_tab_columns
So what do ya do? Query it as though it were a table.
SELECT * FROM user_tab_columns WHERE TABLE_NAME='employee'
However, I don't know why you'd want to query this after the fact given your code, as you already know the column names and could easily just hardcode them in.

Fetching data from MySQL database to HTML dropdown list

I have a web site that contains an HTML form, in this form I have a dropdownlist with list of agents that works in the company, I want to fetch data from MySQL database to this dropdownlist so when you add a new agent his name will appear as an option in the drop down list.
<select name="agent" id="agent">
</select>
To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.
// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query
echo '<select name="DROP DOWN NAME">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.htmlspecialchars($row['something']).'">'.htmlspecialchars($row['something']).'</option>';
}
echo '</select>';// Close your drop down box
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
You need to fetch all rows from the database and then iterate over them, displaying a new <option> for each one of them. Pay attention to avoid XSS by using htmlspecialchars().
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
// Select all values from the table Agents
$stmt = $pdo->prepare("SELECT Id, Name FROM Agents");
$stmt->execute();
echo '<select name="agent" id="agent">';
// For each row from the DB display a new <option>
foreach ($stmt as $row) {
// value attribute is optional if the value and the text is the same
echo '<option value="'.htmlspecialchars($row['Id']).'">';
echo htmlspecialchars($row['Name']); // The text to be displayed to the user
echo '</option>';
}
echo '</select>';
If you want to preselect one of the values, then you need to apply selected attribute to one of the <options>:
$selected = 'Somebody';
echo '<select name="agent" id="agent">';
foreach ($stmt as $row) {
if ($selected === $row['Name']) {
echo '<option value="'.htmlspecialchars($row['Id']).'" selected >';
} else {
echo '<option value="'.htmlspecialchars($row['Id']).'">';
}
echo htmlspecialchars($row['Name']);
echo '</option>';
}
echo '</select>';
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
HTML option tag
Getting Datafrom MySQL database
hope this helps :)

Categories