I have a small problem with MySQL tables pushed into a HTML table.
Here is my SELECT on the database:
$result = mysql_query("
SELECT dat_eb_registrants.id, dat_eb_registrants.first_name, dat_eb_registrants.last_name, dat_eb_registrants.email, dat_eb_registrants.comment, dat_eb_registrants.amount, dat_eb_registrants.published, dat_eb_registrants.transaction_id, dat_eb_registrants.register_date, GROUP_CONCAT(dat_eb_field_values.field_value SEPARATOR '</td><td>')
FROM dat_eb_registrants LEFT JOIN dat_eb_field_values ON dat_eb_registrants.id=dat_eb_field_values.registrant_id
WHERE `event_id` >= 20 AND `event_id` <= 25
GROUP BY dat_eb_registrants.id
ORDER BY $sort $ascdsc
");
Which is pushed into my HTML table using this:
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[9] . "</td>";
echo "<td>";
Now, my problem is the fact that this fills my table with a few rows from dat_eb_field_values.field_value, and I can't get other rows ($row[0] to $row[8]) in-between these results.
For example if my $values come from dat_eb_field_values.field_value and my $data comes from dat_eb_registants. This would be my table:
| header 1 | header 2 | header 3 | header 4 | header 5 | header 6 |
-------------------------------------------------------------------
| $value1 | $value2 | $data3 | $value4 | $data1 | $data2 |
| $value1 | $value2 | $data3 | $value4 | $data1 | $data2 |
| $value1 | $value2 | $data3 | $value4 | $data1 | $data2 |
Thanks in advance! Laurent
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
foreach($row AS $val)
echo "<td>" . $val . "</td>";
echo "<td>";
}
that should do
Instead of echoing out the data of $row[9] place it in a array, then spit it out when you feel it's necessary (and after you've checked for the other elements)
For example change this:
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[9] . "</td>";
echo "<td>";
To this:
while ($row = mysql_fetch_row($result)) {
$myArray[] ="<tr><td>" . $row[9] . "</td>""<td>";
instead of mysql_fetch_row use mysql_fetch_array
and
ORDER BY $sort $ascdsc change it to
ORDER BY '".$sort."', '".$ascdsc."'
exemple :
by using mysql_fetch_array try echo this
echo $row['dat_eb_registrants.id'] ;
your sql is hard to read
use this
SELECT dr.id, dr.first_name, dr.last_name, dr.email, dr.comment, dr.amount, dr.published, dr.transaction_id, dr.register_date, GROUP_CONCAT(df.field_value SEPARATOR '</td><td>')
FROM dat_eb_registrants dr
LEFT JOIN dat_eb_field_values df
ON dr.id=df.registrant_id
WHERE `event_id` >= 20 AND `event_id` <= 25
GROUP BY dr.id
ORDER BY '".$sort."', '".$ascdsc."'
but you have accepted the answer here !!
Related
I am connected to my database.
Created a drop down-box. Which works fine:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Now I am stuck trying to put the values from table Customer into an array
Which looks like this:
$types = array (
'A' => 10.99,
'B' => 4.99,
'C' => 13.99);
What I intend to do is to create this array where,
Instead of A B C, there are CustomeName and CustomerPrice in place of the price.
The Customer table has
+----------------+-----------------+---------------+
| Customer_ID | CustomerName | CustomerPrice |
+----------------+-----------------+---------------+
| 1 | A | 10.99 |
| 2 | B | 4.99 |
| 3 | C | 13.99 |
+----------------+-----------------+---------------+
Please help
You basically do the same thing you did with the drop down except to generate the array. You could do it in the same loop:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
$array = array();
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
$array[$row['CustomerName']] = $row['CustomerPrice'];
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Hope this helps
I am trying write code in PHP with a Mysql database, and the problem is I want to show all rows with a same column value. for example like this:
id | Name | age | Location | type
----+----------+-----+----------+------
1 | Ane | 22 | SG | 1
2 | Angi | 19 | IND | 2
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
6 | Mikha | 25 | JP | 2
I want only show the rows with value in column type = 1 or value in column Location and showing as table in html view.
The result what I want is like this:
id | Name | age | Location | type
---+----------+-----+----------+------
1 | Ane | 22 | SG | 1
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
This is my code:
<?php
$con = mysqli_connect("localhost","root","","testuser");
$query = mysqli_query("SELECT * FROM `usersdata` WHERE `type`='1'");
$result = mysqli_query($con,$query);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
But I got errors like this:
Warning: mysqli_query() expects at least 2 parameters, 1 given in www.myweb.com\users_list\type.php on line 94 << this point "$query" line
Warning: mysqli_query(): Empty query in www.myweb.com\users_list\type.php on line 95 << this point "$result" line
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in www.myweb.com\users_list\type.php on line 109 << this point "while ($row=" line
I was trying understand and still i don't get it, anyone can help me please?! thanks.
Change
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
to
$query = "SELECT * FROM usersdata WHERE type='1'";
EDIT
Just for explanation:
mysqli_query takes 2 arguments: connection and query. I assumed that you wanted to just create query string in this line where this error arouse since it is used one line furter as a query string.
Issue is in bolow lines.
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
$result = mysqli_query($con,$query);
You have 2 ways to resolve this.
1. $query = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($con,$query);
2. $query = mysqli_query($con,"SELECT * FROM `usersdata` WHERE `type`='1'");
Try this one. It should be working fine
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($conn, $sql);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I have a mini game which is written in PHP. I want to build a highscore section for it. But I can't echo datas properly. My database
+--------+----------+----------------------------------+---------------------+------+------+
| UserID | Username | Password | EmailAddress | win | lost |
+--------+----------+----------------------------------+---------------------+------+------+
| 1 | utku | e10adc3949ba59abbe56e057f20f883e | utku#utku.com | 3 | 6 |
| 2 | utku2 | e10adc3949ba59abbe56e057f20f883e | utku#sda.com | 5 | 15 |
| 3 | utku3 | e10adc3949ba59abbe56e057f20f883e | sad | 0 | 0 |
+--------+----------+----------------------------------+---------------------+------+------+
I'm trying to echo them with this code (I found it in another question's topic)
<?php include "base.php"; ?>
<?
$query="SELECT Username,win,lost FROM users ORDER BY win";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr><br>';
}
?>
It prints datas like this
utku3utku30000
utkuutku3366
utku2utku2551515
But I want to print them in this form
Username Win Lost
utku2 5 15
utku 3 6
utku3 0 0
How can I do it. I'm new on PHP
You should not use mysql_ as it is outdated and will be removed in future versions of php.
You should switch to mysqli_ or PDO. (Overview of the MySQL PHP drivers > Choosing an API)
Your problem is:
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
MYSQL_BOTH: [...]By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.[...]
That's why you get each column twice.
A quick fix would be using MYSQL_NUM or MYSQL_ASSOC:
mysql_fetch_array($results, MYSQL_ASSOC)
You should not print tr, td without table tag. Also you did not added th. Can try this
echo '<table><tr><th>User Name</th><th>Win</th><th>Lost</th></tr>';
while ($row = mysql_fetch_array($results)) {
echo '<tr><td>'.$row['Username'].'</td><td>'.$row['win'].'</td><td>'.$row['lost'].'</td></tr>';
}
echo '</table>';
You don't need the foreach loop because the while loop is doing the recursive iteraction, that's why you have twice results:
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
echo '<td>' . htmlspecialchars($field['Username']) . '</td>';
echo '<td>' . htmlspecialchars($field['win']) . '</td>';
echo '<td>' . htmlspecialchars($field['lost']) . '</td>';
echo '</tr><br>';
}
I have two tables, result and gp.
In the result table I have something like this:
|id||student_id ||course_code||grade||session ||level||semester|
|1 ||TR/2213234561||MAT111 ||A ||2009/2010||100 ||first |
|2 ||TR/2213234561||MAT112 ||B ||2009/2010||100 ||first |
|3 ||TR/2213234561||MAT113 ||C ||2009/2010||100 ||first |
|4 ||TR/2213234567||MAT111 ||D ||2009/2010||200 ||first |
|5 ||TR/2213234567||MAT112 ||C ||2009/2010||200 ||first |
|6 ||TR/2213234567||MAT113 ||C ||2009/2010||200 ||first |
Then gp table
|id||student_id ||session ||level||semester||gp |
|1 ||TR/2213234561||2009/2010||100 ||first ||4.2|
|2 ||TR/2213234567||2009/2010||100 ||first ||3.5|
|3 ||TR/2213234561||2010/2011||200 ||first ||4.2|
|4 ||TR/2213234567||2010/2011||200 ||first ||3.5|
What I want is like this:
|Matriculation||MAT111||MAT112||MAT113||MAT114||GP |
|TR/2213234561||A ||B ||D ||C ||4.2|
|TR/2213234567||C ||D ||E ||F ||3.5|
The course code are not constant - it depends on the course registered by the students
I have done this:
<?php
$rst1 = mysql_query("select distinct course_code from result ", $conn);
echo "<table callspacing='4'>";
echo "<tr>";
echo "<td> Matriculation Number </td>";
$c_code = array();
while ($row = mysql_fetch_array($rst1))
{
$c_code[] = $row['course_code'];
}
foreach($c_code as $c_code)
{
echo "<td>" .$c_code. "</td>";
}
$sql ="SELECT result.student_id,
MAX(CASE WHEN course_code = ' $c_code' THEN grade END) $c_code,
gp.CTC
FROM result
JOIN gp
ON gp.student_id = result.student_id
GROUP
BY student_id";
echo "<td> GP</td>";
$rst = mysql_query("$sql",$conn) or die(mysql_error());
while ($row = mysql_fetch_array($rst))
{
echo "</tr>";
echo "<tr>";
echo "<td>" .$row['student_id']. "</td>";
echo "<td>" .$row[$c_code]. "</td>";
}
echo "<td>" .$row[$c_code]. "</td>";
echo "<td>" .$row['CTC']. "</td>";
echo"</tr>";
echo "</table>";
?>
The first query was to get the course code, since the courses are not constants.
with that code, I got something like this:
|Matriculation||MAT111||MAT112||MAT113||MAT114||GP|
|TR/2213234561|
|TR/2213234567|
But I wanted
|Matriculation||MAT111||MAT112||MAT113||MAT114||GP |
|TR/2213234561||A ||B ||D ||C ||4.2|
|TR/2213234567||C ||D ||E ||F ||3.5|
Any suggestion or direction will be highly appreciated.
What you wish to do is known as "pivoting" your data and is something for which some other RDBMS have native support, but MySQL does not (by design, as the developers feel that such manipulations belong in the presentation layer).
However, you have a few options:
Construct a rather horrible MySQL query to perform the pivoting operation manually:
SELECT student_id AS Matriculation, MAT111, MAT112, gp AS GP
FROM gp
NATURAL JOIN (
SELECT student_id, grade AS MAT111
FROM result
WHERE course_code = 'MAT111'
) AS tMAT111
NATURAL JOIN (
SELECT student_id, grade AS MAT112
FROM result
WHERE course_code = 'MAT112'
) AS tMAT112
-- etc.
WHERE level = #level AND semester = #semester
If you choose to go down this path, you can make your life slightly easier by generating this query automatically, using either a looping construct in PHP or a prepared statement in MySQL.
Here is one way that you could do that in PHP:
Obtain a list of courses:
$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', $user, $password);
$qry = $dbh->query("SELECT DISTINCT course_code FROM result [WHERE ...]");
$courses = $qry->fetchAll(PDO::FETCH_COLUMN, 0);
Loop over the results, constructing the above SQL:
mb_regex_encoding($charset);
$columns = mb_ereg_replace('`', '``', $courses);
$sql = "
SELECT student_id AS Matriculation, `".implode("`,`", $columns)."`, gp AS GP
FROM gp";
foreach ($columns as $column) $sql .= "
NATURAL JOIN (
SELECT student_id, grade AS `$column`
FROM result
WHERE course_code = ?
) AS `t$column`";
$sql .= "
WHERE level = ? AND semester = ?";
Execute the SQL, passing in the array of courses as parameters:
$qry = $dbh->prepare($sql);
$params = $courses;
array_push($params, $level, $semester);
$qry->execute($params);
Output the results:
echo "<table>";
echo "<tr>";
for ($i = 0; $i < $qry->columnCount(); $i++) {
$meta = $qry->getcolumnMeta($i);
echo "<th scope='col'>" . htmlentities($meta['name']) . "</th>";
}
echo "</tr>";
while ($row = $qry->fetch(PDO::FETCH_NUM)) {
echo "<tr>";
foreach ($row as $field) echo "<td>" . htmlentities($field) . "</td>"
echo "</tr>";
}
echo "</table>";
Do the above as a one-off operation so that the structure of your MySQL database is changed to more closely reflect this desired layout (easy once table is converted, but may impact other uses of the database):
CREATE TABLE StudentGrades (PRIMARY KEY('Matriculation'))
SELECT student_id AS Matriculation, MAT111, MAT112, gp AS GP
-- etc. as above
Alternatively, you can create a VIEW which is a sort of "virtual table" structured in this way based on the underlying table.
Pivot the data manually in PHP (relatively tedious).
I'm building a form with php/mysql. I've got a table with a list of locations and sublocations. Each sublocation has a parent location. A column "parentid" references another locationid in the same table. I now want to load these values into a dropdown in the following manner:
--Location 1
----Sublocation 1
----Sublocation 2
----Sublocation 3
--Location 2
----Sublocation 4
----Sublocation 5
etc. etc.
Did anyone get an elegant solution for doing this?
NOTE: This is only psuedo-code.. I didn't try running it, though you should be able to adjust the concepts to what you need.
$parentsql = "SELECT parentid, parentname FROM table";
$result = mysql_query($parentsql);
print "<select>";
while($row = mysql_fetch_assoc($result)){
$childsql = "SELECT childID, childName from table where parentid=".$row["parentID"];
$result2 = mysql_query($childsql);
print "<optgroup label=\".$row["parentname"]."\">";
while($row2 = mysql_fetch_assoc($result)){
print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n";
}
print "</optgroup>";
}
print "</select>";
With BaileyP's valid criticism in mind, here's how to do it WITHOUT the overhead of calling multiple queries in every loop:
$sql = "SELECT childId, childName, parentId, parentName FROM child LEFT JOIN parent ON child.parentId = parent.parentId ORDER BY parentID, childName";
$result = mysql_query($sql);
$currentParent = "";
print "<select>";
while($row = mysql_fetch_assoc($result)){
if($currentParent != $row["parentID"]){
if($currentParent != ""){
print "</optgroup>";
}
print "<optgroup label=\".$row["parentName"]."\">";
$currentParent = $row["parentName"];
}
print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n";
}
print "</optgroup>"
print "</select>";
Are you looking for something like the OPTGROUP tag?
optgroup is definitely the way to go. It's actually what it's for,
For example usage, view source of http://www.grandhall.eu/tips/submit/ - the selector under "Grandhall Grill Used".
You can use and space/dash indentation in the actual HTML. You'll need a recusrive loop to build it though. Something like:
<?php
$data = array(
'Location 1' => array(
'Sublocation1',
'Sublocation2',
'Sublocation3' => array(
'SubSublocation1',
),
'Location2'
);
$output = '<select name="location">' . PHP_EOL;
function build_items($input, $output)
{
if(is_array($input))
{
$output .= '<optgroup>' . $key . '</optgroup>' . PHP_EOL;
foreach($input as $key => $value)
{
$output = build_items($value, $output);
}
}
else
{
$output .= '<option>' . $value . '</option>' . PHP_EOL;
}
return $output;
}
$output = build_items($data, $output);
$output .= '</select>' . PHP_EOL;
?>
Or something similar ;)
Ideally, you'd select all this data in the proper order right out of the database, then just loop over that for output. Here's my take on what you're asking for
<?php
/*
Assuming data that looks like this
locations
+----+-----------+-------+
| id | parent_id | descr |
+----+-----------+-------+
| 1 | null | Foo |
| 2 | null | Bar |
| 3 | 1 | Doe |
| 4 | 2 | Rae |
| 5 | 1 | Mi |
| 6 | 2 | Fa |
+----+-----------+-------+
*/
$result = mysql_query( "SELECT id, parent_id, descr FROM locations order by coalesce(id, parent_id), descr" );
echo "<select>";
while ( $row = mysql_fetch_object( $result ) )
{
$optionName = htmlspecialchars( ( is_null( $row->parent_id ) ) ? "--{$row->descr}" : "----{$row->desc}r", ENT_COMPAT, 'UTF-8' );
echo "<option value=\"{$row->id}\">$optionName</option>";
}
echo "</select>";
If you don't like the use of the coalesce() function, you can add a "display_order" column to this table that you can manually set, and then use for the ORDER BY.