How to Echo Datas From Mysql Properly - php

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>';
}

Related

how to import person's name with (') into sql server

I have this table on saprfc, and I import it into the sql server. But the person's name with (') does not enter the sql server. (Nanang Ma'ruf and Fat'khah Dwi)
ID | FEE | NAME | PERIOD
000711 | 204000 | YUDI MANDALA | 201807
000790 | 84000 | NANANG MA'RUF | 201807
001171 | 151500 | SARJANA | 201807
012314 | 89000 | FAT'KHAH DWI | 201807
my code:
foreach($tmp as $item)
{
$i++
$a[$i] = $item['id'];
$b[$i] = $item['FEE'];
$c[$i] = $item['NAME'];
$d[$i] = $item['PERIOD'];
echo '<tr>';
echo '<td>'. $item['ID'].'</td>';
echo '<td>'. $item['FEE'].'</td>';
echo '<td>'. $item['NAME'].'</td>';
echo '<td>'. $item['PERIOD'].'</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
</div>
<?php
if (isset($_POST["import"]))
{
if ($FI_HPs!=0)
{
for ($i=1;$i<=$FI_HPs;$i++)
{
$query = mssql_query("INSERT INTO SISDM (id, fee, name, period) VALUES ('$a[$i]','$b[$i]','$c[$i]','$d[$i]')");
}
}
}
You can use mysqli_real_escape_string().
PS: i'll use PDO instead of mssql_query(), 'cause it's removed in PHP7 so you can use PDO::quote() instead of previous escape function.

PHP : show all rows in MySQL that contain the same value in a column

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>";
?>

How to display multiple records with same id in html table in single row(in <td>)?

I have sql data result set having records as follows
id | name | hobbies
------------------------------------
1 | RAVI | PLAYING CRICKET
------------------------------------
1 | RAVI | LISTENING MUSIC
------------------------------------
2 | REENA | BADMINTON
------------------------------------
I am displaying this data in view by using html table.
Whereas my requirement is, I want to display as follows
id | name | hobbies
------------------------------------
1 | RAVI | PLAYING CRICKET
| | LISTENING MUSIC
------------------------------------
2 | REENA | BADMINTON
------------------------------------
meaning I want to display records with id 1 into one <td>
I am using php foreach loop to display result.
How can I achieve this?
My current code is as follows and is results into same as my first table whereas I want my view as in the second table.
<table class="table table-striped">
<tr >
<th>ID</th>
<th>Name</th>
<th>Hobbies</th>
</tr>
foreach($result as $row)
{
echo "<tr>
<td>".$row->id."</td>
<td>". $row->name."</td>
<td>". $row->hobbies."</td>
</tr>";
}
</table>
A quick way to approach this would be to modify your MySQL query to use GROUP_CONCAT(hobbies) to group all of a user's hobbies together. The query would look something like:
SELECT
id, name, GROUP_CONCAT(hobbies) AS hobbies
FROM
your_table
GROUP BY
id
This will group all of a user's hobbies in a comma-delimited list. To display it, you can use PHP's explode() and iterate over that:
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->id . '</td>';
echo '<td>' . $row->name . '</td>';
echo '<td>';
$hobbies = explode(',', $row->hobbies);
foreach ($hobbies as $hobby) {
// output each hobby and decorate/separate them however you'd like
echo $hobby . '<br />';
}
echo '</td>';
echo '</tr>';
}
If you don't want the inner loop (or the ending <br /> that will pad the hobbies), you can use str_replace() instead:
echo str_replace(',', '<br />', $result['hobbies']);
This post may help you: Concatenate many rows into a single text string?
Just replace the , with </br>.
in each iteration, you must save the last ID, in the next iteration you must check it whether its value has been changed or not. Something like this:
$res = $this->db->query('.....');
$last_ID = '';
foreach ($res->result() as $row) {
if ($row->id != $last_ID) {
if (strlen($last_ID)>0) echo '</td></tr>';
echo '<tr>';
echo '<td>$row->id</td>';
echo '<td>$row->name</td>';
echo '<td>$row->hobbies';
} else {
echo '<br />'.$row->hobbies;
}
$last_ID = $row->id;
}
if ($res->num_rows() > 0) echo '</td></tr>';
Supposing you have your row in $row var and the ID is $row["ID"]
?>
<td id="<php echo $row["id"]; ?>">
<?php echo $row["id"]; ?>
</td>
<?php

MYSQL PHP Output sorting, get values inbetween output

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 !!

Nested dropdown

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.

Categories