Run Query in PHP to display in table - php

I'm trying to create a league table, the query works in phpmyadmin. But I cannot display it in a table using php.
I think the issue is that I'm not running the query the correct way. When I run the code I get "league table query not populated"
Please can you give some advice on running this:
<?php
$sql =
"SELECT player_name,
SUM(win+draw+lose) AS Played,
SUM(win) AS Won,
SUM(draw) AS Drawn,
SUM(lose) AS Lost,
SUM(`for`) AS `Goals For`,
SUM(`against`) AS `Goals Against`,
SUM(cast(`for`AS SIGNED) - cast(`against`AS SIGNED)) AS `Goal Difference`,
SUM((win*3)+(draw)+extra_points) AS Points,
ROUND((SUM((win*3)+draw))/SUM((win+draw+lose)*3)*100,1) AS Record
FROM appearances
WHERE season_id = 4
GROUP BY player_name
ORDER BY Points DESC,
Played ASC,
`Goal Difference` DESC, `Goals For` DESC,
player_name ASC[...]";
if (!$sql) {
echo 'sql query has not worked';
}else {
$leaguetable = mysql_query($sql);
if (!$leaguetable){
echo 'league table query not populated';
} else {
$records = mysql_fetch_array($leaguetable);
If (!$records) {
echo 'records have not been placed in assoc array';
}
else {
echo "<tr width='600'>";
echo "<td>" . $records["player_name"] . "</td>";
echo "<td>" . $records["Played"] . "</td>";
echo "<td>" . $records["Won"] . "</td>";
echo "<td>" . $records["Drawn"] . "</td>";
echo "<td>" . $records["Lost"] . "</td>";
echo "<td>" . $records["Goals For"] . "</td>";
echo "<td>" . $records["Goals Against"] . "</td>";
echo "<td>" . $records["Goal Difference"] . "</td>";
echo "<td>" . $records["Points"] . "</td>";
echo "<td>" . $records["Record"] . "</td>";
echo "</tr>";
//while ($records = mysql_fetch_assoc($sql));
}
}
}
?>
When I run the above I get "league table query not populated"
Thanks in advance for your help
I've just tried the PDO method and its still not displaying the records, i believe there is a database connection, here's the code
<?php
require 'pdoconnect.php';
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$stmt = $db->prepare("SELECT player_name,
SUM(win+draw+lose) AS Played,
SUM(win) AS Won,
SUM(draw) AS Drawn,
SUM(lose) AS Lost,
SUM(`for`) AS `Goals For`,
SUM(`against`) AS `Goals Against`,
SUM(cast(`for`AS SIGNED) - cast(`against`AS SIGNED)) AS `Goal Difference`,
SUM((win*3)+(draw)+extra_points) AS Points,
ROUND((SUM((win*3)+draw))/SUM((win+draw+lose)*3)*100,1) AS Record
FROM appearances
WHERE season_id = 4
GROUP BY player_name
ORDER BY Points DESC,
Played ASC,
`Goal Difference` DESC, `Goals For` DESC,
player_name ASC[...]");
$stmt->execute();
$result = $stmt->fetchAll(pdo::FETCH_ASSOC);
while($row = $result){
echo "<tr width='600'>";
echo "<td>" . $row['player_name'] . "</td>";
echo "<td>" . $row['Played'] . "</td>";
echo "<td>" . $row['Won'] . "</td>";
echo "<td>" . $row['Drawn'] . "</td>";
echo "<td>" . $row['Lost'] . "</td>";
echo "<td>" . $row['Goals For'] . "</td>";
echo "<td>" . $row['Goals Against'] . "</td>";
echo "<td>" . $row['Goal Difference'] . "</td>";
echo "<td>" . $row['Points'] . "</td>";
echo "<td>" . $row['Record'] . "</td>";
echo "</tr>";
//while ($records = mysql_fetch_assoc($sql));
}
?>

Please replace this statement
$leaguetable = mysql_query($sql);
with
$leaguetable = mysql_query($sql) or die(mysql_error());
to check the reason due to which query failed

Not a real andwer and I don't know which version of PHP you are using but you might consider the warning on http://php.net/manual/en/function.mysql-query.php
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

you can do somting like this..
<!doctype html>
<html>
<head></head>
<body>
<table>
<tr>
<?php
header('Content-Type: text/html; charset=UTF-8');
mysql_connect("localhost", "user", "password");
mysql_select_db("alarm");
mysql_query( "SET NAMES utf8" );
mysql_query( "SET CHARACTER SET utf8" );
$dave = mysql_query("select blablabla as ab");
while ($row = mysql_fetch_assoc($dave)) {
echo $row['ab'];
echo "<td>";
.
. put where you want..
.
echo "<tr>";
}
?>
</body>
</html>

You have to connect to your database before issuing any query to it:
Try this on the beginning of your script (replace localhost, mysql_user and mysql_password with your servers data):
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_link= mysql_select_db('database_name', $link);
if (!$db_link) {
die ('Can\'t use database_name: ' . mysql_error());
}
See http://php.net/manual/en/function.mysql-connect.php
And http://php.net/manual/en/function.mysql-select-db.php for more detail.

Related

Trying to get results to show on table with PDO Statement

I am new to PDO trying to figure how to get this to work with PDO. I have it working with MYSQL I maybe confused how PDO works. I am getting a blank page any ideas on how I can go about getting all the results of received records. I see tutorials on PDO but when I do it it is for single records with an array.
<?php
require_once("../db_connect.php");
$stmt = $db->prepare ("SELECT * FROM requests WHERE status='Received'");
echo"Received Requests";
echo "<br><br>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo("<table bgcolor=F2F2F2 width=1080 border='2'>");
echo("<br><tr><th>Id</th><th>Update</th><th>LanID</th><th>Name</th><th>Location</th><th>Manager</th><th>request</th><th>Description</th><th>request_comments</th><th>Status</th><th>Comments</th><th>Completed User</th><th>Completed Date</th></tr>");
echo("<tr>");
echo "<td>". $row['id'] . "</td>"
."<td><a href='../update.php?id=" . $row['id'] . "'>Update</a></td>"
."<td>" . $row['lanId'] . "</td> "
. "<td>". $row['name'] . "</td>"
. "<td>". $row['department'] . "</td>"
. "<td>" . $row['manager'] . "</td>"
. "<td>" . $row['request'] ."</td>"
. "<td>" . $row['request_description'] ."</td>"
. "<td>" . $row['request_comments'] ."</td>"
. "<td>" . $row['status'] ."</td>"
. "<td>" . $row['comments'] ."</td>"
. "<td>" . $row['compUser'] ."</td>"
. "<td>" . $row['compDt'] ."</td>";
echo '</tr>';
}
echo("</table>");
?>
<html>
<head>
<meta http-equiv="refresh" content="5" >
<title>
</title>
</head>
<body background="../images/background.jpg">
</body>
</html>
db_connect.php
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "systems_requests";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
?>
You forgot to execute your prepared statement.
Please use $stmt->execute () before using $stmt->fetch ()
Also please fetch like so:
$requests = $stmt->fetch (PDO::FETCH_ASSOC);
foreach ($requests as $request) {
echo $request["whateverKeyYouWant"];
}

PHP mysql query returns a blank screen

I've commented out the bottom part, and the SQL query works fine. Its the displaying of the query where the error is coming from i believe.
$host = "127.0.0.1";
$user = "root";
$pass = "Toom13371!";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
// 2. Selecting DB.
$dbname = "filters";
mysql_select_db($dbname);
// 3. Build/Test SQL Query
$sql = ("select * from filter_bandpass where start_passband=" . $_POST['Lowfreq'] . " and stop_passband='" . $_POST['Highfreq'] . "'");
//echo $sql; //Comment/Uncomment to test sql query.
// 4. Retrieve info from MySQL.
$query = mysql_query($sql);
// 5. Display Query.
echo "<table border='1'>
<tr>
<th>Low Frequency</th>
<th>High Frequency</th>
</tr>";
while($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['Lowfreq'] . "</td>";
echo "<td>" . $row['Highfreq'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Any help would be appreciated, I'm sure it's going to be some small stupid error i've over looked.
Thanks in advance :)
I'm guessing, based on your query, that you need to change this
mysql_select_db($dbname);
to
mysql_select_db($dbname, $connection);
and
while($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['Lowfreq'] . "</td>";
echo "<td>" . $row['Highfreq'] . "</td>";
echo "</tr>";
}
to
while($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['start_passband'] . "</td>";
echo "<td>" . $row['stop_passband'] . "</td>";
echo "</tr>";
}
Change line
mysql_select_db($dbname);
to
mysql_select_db($dbname, $connection);
Also before query check
$_POST['Lowfreq'] and $_POST['Highfreq']
If there is no value in these variables query will must return empty.
In your query there should not brackets for string.
$sql = ("select * from filter_bandpass where start_passband=" . $_POST['Lowfreq'] . " and stop_passband='" . $_POST['Highfreq'] . "'");
should be:
$sql = "select * from filter_bandpass where start_passband=" . $_POST['Lowfreq'] . " and stop_passband='" . $_POST['Highfreq'] . "'";

PHP - SQL select Data display

<html>
<head>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8" />
<title>Using file functions PHP</title>
</head>
<body>
<h1>Web Development - Lab05</h1>
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$queryResult = "SELECT car_id, make, model, price FROM cars";
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array($queryResult);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
</body>
</html>
This is doing my head in, I cannot figure out why it will not display the actual data apart from the Table header. No matter what I used.
I have tried mysqli_fetch_array, mysqli_fetch_row, mysqli_fetch_assoc but nothing works.
Help and explanation why it was not displaying the data would be much appreciated :)
First: You aren't running a query, you are only putting the query text in a variable. You need to use mysqli_query.
Second: You should add mysqli_fetch_array to the loop.
For example:
while($displayrow = mysqli_fetch_array($queryResult))
{
}
Otherwise you are only getting the first row.
Third: Array keys are case sensitive. There is no $row['ID'], as Jeribo pointed out, it is $row['car_id'] as referenced in your query. $row['Make'] is not the same as $row['make'].
Please Precision to names of field in Query ( car_id,make,...)
while($displayrow= mysql_fetch_assoc($queryResult) )
{
echo "<tr>";
echo "<td>" . $displayrow['car_id'] . "</td>";
echo "<td>" . $displayrow['make'] . "</td>";
echo "<td>" . $displayrow['model'] . "</td>";
echo "<td>" . $displayrow['price'] . "</td>";
echo "</tr>";
}
If you want to query outside you still have to set it in the loop:
$result = $db->query($queryResult)
while($row = $result ->fetch_assoc()){
...
}
a Good Tutorial is shown here: http://codular.com/php-mysqli
$row needs to be initialized so why don't you try:
while($row = mysqli_fetch_array($queryResult))
{
....
}
You have to get the result set first and then try fetching array from result set
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$query = "SELECT car_id, make, model, price FROM cars";
$resultSet=mysqli_query($dbconnect,$query)
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array( $resultSet);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
http://www.w3schools.com/php/func_mysqli_fetch_array.asp

MySQL INSERT query returns "You have an error in your SQL syntax" error

I have got following error in a simple PHP page when I tried to insert a row in a table "userstbl"
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'userstbl\' (\'usr_name\', \'usr_pwd\', \'usr_fname\', \'usr_lname\') VALUES (\' at line 1
Here is the code:
$con = mysqli_connect("localhost","root","","test_sms");
if (mysqli_connect_errno())
{
echo "Failed to connect:" . mysqli_connect_error();
}
$value = "INSERT INTO 'userstbl' ('usr_name', 'usr_pwd', 'usr_fname', 'usr_lname') VALUES ('Aftab','xyz','Aftab','Hussain')";
$sqlin = mysql_prep($value);
if (!mysqli_query($con, $sqlin)){
die ('Error: ' . mysqli_error($con));
}
$sqlot = "SELECT * FROM 'usertbl'";
$sqlo = mysql_prep($sqlot);
$sqlout = mysqli_query($con , $sqlo);
echo "<table border='1'><tr><th>ID</th><th>Username</th><th>Password</th><th>First Name</th><th>Last Name</th></tr>";
while ($row = mysqli_fetch_array($sqlout));
{
echo "<tr>";
echo "<td>" . $row['usr_id'] . "</td>";
echo "<td>" . $row['usr_name'] . "</td>";
echo "<td>" . $row['usr_pwd'] . "</td>";
echo "<td>" . $row['usr_fname'] . "</td>";
echo "<td>" . $row['usr_lname'] . "</td>";
echo "</tr>";
}
mysqli_close($con);
?>
If you want to escape column and table names use backticks, not quotes
INSERT INTO `userstbl` (`usr_name`, usr_pwd, usr_fname, usr_lname)
VALUES ('Aftab', 'xyz', 'Aftab', 'Hussain')
try
$con = mysqli_connect("localhost","root","","test_sms");
if (mysqli_connect_errno())
{
echo "Failed to connect:" . mysqli_connect_error();
}
$value = "INSERT INTO userstbl (usr_name, usr_pwd, usr_fname, usr_lname) VALUES ('Aftab','xyz','Aftab','Hussain')";
$sqlin = mysql_prep($value);
if (!mysqli_query($con, $sqlin)){
die ('Error: ' . mysqli_error($con));
}
$sqlot = "SELECT * FROM usertbl";
$sqlo = mysql_prep($sqlot);
$sqlout = mysqli_query($con , $sqlo);
echo "<table border='1'><tr><th>ID</th><th>Username</th><th>Password</th><th>First Name</th><th>Last Name</th></tr>";
while ($row = mysqli_fetch_array($sqlout));
{
echo "<tr>";
echo "<td>" . $row['usr_id'] . "</td>";
echo "<td>" . $row['usr_name'] . "</td>";
echo "<td>" . $row['usr_pwd'] . "</td>";
echo "<td>" . $row['usr_fname'] . "</td>";
echo "<td>" . $row['usr_lname'] . "</td>";
echo "</tr>";
}
mysqli_close($con);
?>

Select 2 tables in one php select statement

I have two tables in mysql
practice_sheets and parent_pin
And I want to use one select statement and get data from both tables.
I have tried
$result = mysqli_query($con,"SELECT * FROM practice_sheets AND parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
and also:
$result = mysqli_query($con,"SELECT * FROM practice_sheets, parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
I've never tried to do this before and the previous solutions are what I found searching.
Update
I think it would help if I included my full code. the table data is going into a table on my page. the student_name field from the practice_sheets and parents_student from parent_pin will be matched.
<?php
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM practice_sheets
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
$numrows = mysqli_num_rows($result);
if($numrows == 0) {
echo "<div class='alert alert-danger'>";
echo "No Entries, See your instructor for details.";
echo "</div>";
} else {
echo "<table class='mws-table table-striped table-hover'>";
echo "<thead align='center'>";
echo "<tr>";
echo "<th>Sheet Number</th>";
echo "<th>Total Minutes</th>";
echo "<th>Due Date</th>";
echo "<th>PIN</th>";
echo "<th>View</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody align='center'>";
while($row = mysqli_fetch_array($result)){
if ($row["total_min"]>=$row["required_min"]) {
echo "<tr class='success'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
} else {
echo "<tr class='info'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
mysqli_close($con);
}
?>
$result = mysqli_query($con,"SELECT *
FROM practice_sheets, parent_pin
WHERE student_name = parents_student
AND student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
Use explicit names for WHERE statament, e.g.
$result = mysqli_query("SELECT student_name.practice_sheets FROM practice_sheets AND parent_pin WHERE student_name.practice_sheets = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
MySQL will not AFAIK automatically check where the constraints are and rightly so considering that you may have conflicting names. Note that this is still pseudo code and you will need to change the fetched results accordingly. Usually it is considered to be good practice to also define explicitly the columns you wish to fetch, but otherwise you can use JOIN as well.
And to help writing shorter code, you can also use shorthands for the table names, e.g.
$result = mysqli_query("SELECT student_name.ps AS name, pin.pp AS pin FROM practice_sheets AS ps, parent_pin AS pp WHERE student_name.ps = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
Update
You also have in your updated version an issue. You call mysqli_fetch_array, which returns an ordered (i.e. numbered) array. If you wish to use keyed, use mysqli_fetch_assoc.
And you are closing the MySQL connection at the moment only if the query was successful. Move mysqli_close outside of the brackets.

Categories