<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
Related
I am using this code to get that data from SQL Server database using PHP
<?php
foreach ($dbDB->query($query) as $row) {
echo "<tr>";
echo "<td>" . $row['Country'] . "</td>";
echo "<td>" . $row['OrderNumber'] . "</td>";
echo "<td>" . $row['Region'] . "</td>";
echo "<td>" . $row['ShipDate'] . "</td>";
echo "<td>" . $row['ProducedDate'] . "</td>";
echo "</tr>"; }
?>
I am trying to replace these multiple lines but storing the columns' names in a string for example $_POST['SelectedColumns'].
The values coming into post as comma separated string, For example : Country,OrderNumber,Region,ShipDate,ProducedDate
I have tried this solution but still not working for me.
<?php
$ser="********";
$db="******";
$user="******";
$pass="******";
$query = 'SELECT '.$_POST['SelectedColumns'].' FROM reporting.REPORT_ALL';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=******;Port=1456", $user, $pass);
$row = $_POST["SelectedColumns"];
$rows = explode(",",$row);
/*Here I have the another html code independent of this part */
foreach ($dbDB->query($query) as $dataRow) {
echo "<table>";
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
echo "</table>"; }
?>
Any suggestions please ?
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.
I wanted to fetch the data from the database and wants to store into an array and after storing the data into the array i want to access particular index of the array.
I'm a java developer need to do this in php (which I don't know much).
Basically there are 250 strings in a table i wanted to fetch those 250 strings into and array and wants to access some particular row.
for example :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
**$uname100 = $row[100]; // this is not getting assigned to $uname100 variable**
**echo $row[100]; // here this is not printing**
**echo $uname100; // not even this printing**
mysqli_close($con);
?>
Please check the bold part in the code and help me out. I'm new to php so please dont panic over this.
And also wanted to do something like this :
$ctr=0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$uname[$ctr++] = $row['FirstName']; // AND USING THIS OUTSIDE LOOP
}
echo $uname[90];
Use array construction
$counter=0;
$data = array();
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$data[] = $row['FirstName'];
$counter++;
}
print_r($data);
First solution
$counter=0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$counter++;
$varName='uname'.$counter;
$$varName=$row['FirstName'];
}
echo echo $uname100;
You cannot access the variable $row[100] outside the while loop.
Also $row will not contain an index 100.
It will be containing only $row['FirstName'] or $row['LastName'] inside the while loop
Answer for second part:
$uname = array();
$ctr=0;
while($row = mysqli_fetch_array($result)) {
....
....
$uname[$ctr++] = $row['FirstName']; // AND USING THIS OUTSIDE LOOP
}
if(isset($uname[90])) echo $uname[90];
i am passing images file names via textarea to php script to find information about each image in mysql db .The problem is i am trying to output those image file names that not found in mysql db and inform the user which image file names not found in mysql. my current code fails to output those missing records in db but it correctly outputs information about those images found in db. could any one tell me what i am doing wrong ?
foreach ($lines as $line) {
$line = rtrim($line);
$result = mysqli_query($con,"SELECT ID,name,imgUrl,imgPURL FROM testdb WHERE imgUrl like '%$line'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
//echo $result;
if($result == 0)
{
// image not found, do stuff..
echo "Not Found Image:".$line;
}
while($row = mysqli_fetch_array($result))
{
$totalRows++;
echo "<tr>";
echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['imgPURL'] . "</td>";
echo "<td>" . $row['imgUrl'] . "</td>"; echo "</tr>";
}
};
echo "</table>";
echo "<br>totalRows:".$totalRows;
You can use mysqli_num_rows() in mysqli
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result))
{
$totalRows++;
echo "<tr>";
echo "<td>" . $row['ID'] ."(".$totalRows. ")</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['imgPURL'] . "</td>";
echo "<td>" . $row['imgUrl'] . "</td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='4'>Not Found Image:".$line.'</td></tr>';
}
You want to use mysqli_num_rows
if(mysqli_num_rows($result)) {
// Do your while loop here
}
Use mysqli_num_rows to compare the number of rows in the result set.
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.