I recently set up a lamp server in an attempt to create a website. My code is as follows.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
$query = "SELECT * FROM nes";
$db = mysqli_connect('localhost','root','password','gameRankings');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while ($row < mysqli_fetch_array($result)) {
echo $row['ranking'] . ' ' . $row['name'] . ': ' . $row['review'] . ' ' . $row['releaseYear'] .'<br>';
}
mysqli_close($db);
?>
<h1>PHP connect to MySQL</h1>
</body>
</html>
The program runs fine and outputs the data I want when I run it using php index.php however when I go to load the site into a browser nothing displays except the heading. If I were to move my the $db connector line to the top of the code then not even the heading displays. There are no errors being thrown in the apache logs either. I have no idea what I'm doing wrong here!
Replace
$row = mysqli_fetch_array($result);
while ($row < mysqli_fetch_array($result)) {
With
while ($row = mysqli_fetch_array($result)) {
That will update $row each loop, with the value from database, and display the info you want.
Do these two steps and you will get your result .
Remove this statement :
$row = mysqli_fetch_array($result);
Re-write the while statement as :
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
//Your Code
}
If you still got no result , then check your database tables whether they have any records or not .
I wish I had a good answer as to what fixed this but I came in this morning to it functioning properly. I also made the other adjustments that were mentioned. This was my first post and I really appreciate the feedback everyone gave!
Related
This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 years ago.
I have been struggling with this PHP script on my personal web server for quite some time. No matter what I do, or what input I give the HTML form (this PHP script is the action page for that form), I end up with a page that looks like this:
view larger version
Below is my code, which is supposed to get a list of ids of the recipes with a tag matching the user's query, then display a quick overview of the matching recipes to the user, in table format:
<html>
<body>
<title>Recipe Database</title>
<h1>recipe finder</h1>
</body>
</html>
<?
$servername = "localhost";
$username = "root";
$password = "xxxx";
$con = mysqli_connect($servername, $username, $password, "recipes");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tag = $_POST["keyword"];
$query = mysqli_query($con, "SELECT id FROM recipes WHERE tag1 LIKE '$tag'");
$query2 = mysqli_query($con, "SELECT id FROM recipes WHERE tag2 LIKE
'$tag'");
$query3 = mysqli_query($con, "SELECT id FROM recipes WHERE tag3 LIKE'$tag'");
$result = mysqli_fetch_array($query);
$result2 = mysqli_fetch_array($query2);
$result3 = mysqli_fetch_array($query3);
$list = array_merge($result, $result2);
$list = array_merge($list, $result3);
if ($list[0] != ""){
echo "<table>";
for ($i = 0; $i < count($list); $i++) {
echo "<tr>";
$detailquery = mysqli_query($con, "SELECT * FROM recipes WHERE id LIKE
\"$list[$i]\"");
$details = mysqli_fetch_array($detailquery);
print "<h3>" . $details[1] . "</h3>";
print "<p>" . $details[2] . " minutes</p>";
print "<p>" . $details[3] . " servings</p>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No recipe with that tag was found. Try a different tag.";
}
?>
I tested it on several different online syntax checkers and it came out clean. Yes, all other PHP scripts are running fine on my server. Yes, all the other PHP scripts are reading and writing to this database and others on my server without error. Yes, I did try wrapping body and html around the PHP script, it makes no difference. Yes, I have checked for unpaired quotation marks and apostrophes, there are none. Yes, I have tried storing the various queries in separate variables, that did not affect anything.
Any help would be appreciated, I am truly stuck on this one. Thank you!
Oops, it looks like I forgot to have the extended tag
<?php
instead of the short one without "php". My bad for being so oblivious.
I'm currently working on producing a basic content management system. In this code I'm grabbing a list of pages from the database 'posts' and then echoing them out. The purpose of the list is for users to be able to select an existing page and then edit the title & content, however I'm unsure on how I can take data from the selected link and then make my page-edit.php show the correct content to edit accordingly. I've assigned the variable $i to each of the anchor tags which increments throughout the while loop, ideally I'd use $i to SELECT the correct page from the database. I'd like to avoid using jQuery, although I'm assuming that's going to be suggested. Any insight would be great, thanks in advance.
<?php
$connection = mysql_connect('localhost', 'root', 'root');
mysql_select_db('posts');
$query = "SELECT * FROM pages";
$result = mysql_query($query);
$i = 0;
while($row = mysql_fetch_array($result)){
$i++;
echo '' . $row['page_title'] . ' - ' . $i . '' . '</br>';
}
mysql_close();
?>
Use the $i as a GET id variable in the link within the while loop:
echo '<a href="edit-page.php?id=' . $i . '>' . $row['page_title'] . ' - ' . $i . '</a>' . '</br>';
Then you can check for $_GET['id'] so that you know what id/page is to be edited and get the data for that from the database:
if (!empty($_GET['id'])) {
$query = 'SELECT * FROM pages WHERE id=' . $_GET['id'];
...
// Show the form populated with data from the above query.
}
I've kept this very simple to get you started.
Don't forget to look into protecting against SQL Injection and moving away from the deprecated MySQL API to use the MySQLi API or MySQL PDO.
Using this method, you'll need a to make an edit page for each page.
Main php file
<?php $db = mysqli_connect("localhost","user","pass","name");
foreach($this->db->query("SELECT * FROM pages") as $row): ?>
<a onclick="loadPage(<?php echo $row['id']; ?>)">
<?php echo $row['page_title']; ?>
</a>
<?php endforeach; ?>
<script>
function loadPage(id){
$.get('handler.php', { param: id })
.done(function (loaded){
document.getElementById("example").innerHTML = loaded;
});
}
</script>
Handler php file
<?php if(isset($_GET['param'])):
foreach($this->db->query("SELECT * FROM pages") as $row):
catch($_GET['param']){
case 1:
require_once 'edit-data.php';
break;
case 2:
require_once 'edit-data-two.php';
break;
default:
break;
}
endforeach; ?>
edit-data.php = edit the page X
edit-data-two.php = edit the page Y
First I want to explain my application:
I have created an application for my QA work. The application generates a document gets saved as a pdf and added to the server. I have a dynamic table in it that gets save to the database using the implode function separating it as with a comma in the same row as the test case on the database.
It all works fine, but when I want to view the test case I am having trouble to figuring out how to get it to display. I have read plenty of scenarios to use the explode but no luck...
<?php include 'app_database/database.php'; ?>
<?php
if(isset($_POST)){
$step = $_REQUEST['step'];
$url = $_REQUEST['url'];
$pass_fail = $_REQUEST['pass_fail'];
$comment = $_REQUEST['comment'];
$sql1 ="UPDATE qa_testing_application SET step='".implode(',',$step)."',url='" . implode(',',$url) . "',pass_fail='" . implode(',',$pass_fail) . "',comment='" . implode(',',$comment) . "' WHERE test_case_name='$test_case_name'";
$result= mysqli_query($database, $sql1) or die(mysqli_error($database));
}
?>
I am inserting it this way. And i would like to retrieve it from the DB.
I would love to display it as follows:
Please see the link http://i.stack.imgur.com/6aglk.jpg
At the moment i am trying to test and figure out how to display it:
Not sure how to implement a for or foreach function in here as well if thats needed.
$countsteps = 0;
$counturls = 0;
$countpass_fails = 0;
$countcomments = 0;
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
while($fetch=mysqli_fetch_object($result))
{
$step=$fetch->step;
$url=$fetch->url;
$pass_fail=$fetch->pass_fail;
$comment=$fetch->comment;
$steps=explode(",",$step);
$urls=explode(",",$url);
$pass_fails=explode(",",$pass_fail);
$comments=explode(",",$comment);
echo '<td>'.$steps[$countsteps++].'</td>';
echo '<td>'.$urls[$counturls++]."</td>";
echo '<td>'.$pass_fails[$countpass_fails++]."</td>";
echo '<td>'.$comments[$countcomments++]."</td>";
}
So how would I get this to display in a table?
edit:
Oh and this is the error that I get:
Undefined Offset
This error simply says there is no such key exists into given array or you're trying to fetch a value from non-array variable.
To show data into tabular format, you don't need to explode data coming from db. They are already concatenated.
So to show data from db, modify your code as show below:
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
echo '<table>';
echo '<th>Step</th><th>Url</th><th>Pass/Fail</th><th>Comment</th>';
while($fetch=mysqli_fetch_object($result))
{
echo '<tr>';
echo '<td>'.$fetch->step.'</td>';
echo '<td>'.$fetch->url.'</td>';
echo '<td>'.$fetch->pass_fail.'</td>';
echo '<td>'.$fetch->comment.'</td>';
echo '</tr>';
}
echo '</table>';
I'm attempting to extract some data from a database and echo each result. The code below is code that I took from a textbook and then tried to modify to fit my own website that is hosted locally. I cannot see where I'm going wrong, no error messages are shown, just a blank screen when I run the scrip.
<?php #script 9.4 view top 5 recipients
// This script exctracts data from db and then displays each record in a table
DEFINE('SYSPATH','FOO');
require '../application/config/database.php';
require 'mysqli_connect.php';
$q = "SELECT alert_recipient as NAME
FROM alert
LIMIT 5;
";
$r = mysqli_query($dbc,$q);
// $dbc database connection comes from required mysqli_connect.php
if($r)
{
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['name'];
}
}
else {
echo "<p>ERROR</p>".mysqli_error($dbc);
}
?>
The code looks okay except for your echo $row['name'];, note that you are selecting NAME, uppercase.
Change your echo statement to be:
echo $row['NAME'];
because field names quoted within $row array are case sensitive.
(Can't comment yet)
Maybe the script works but there is no results to display. Check your database.
I am creating a table to display on a web page and that table is populated from data in a MySQL database. I am trying to do a couple of things that are making it difficult for me.
First I am trying to have call the PHP code that exists in a separate file in HTML via JavaScript. I think I have that working right but I am not 100% sure (because the table will not display). I think it is working right because some of the code for the table (which is in the PHP file) displays in FireBug.
Second I am trying to make it so the rows alternate colors for easy viewing too. My PHP code so far is below. The table does not display at all in any browser.
$query = "SELECT * FROM employees";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo '<table>';
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$id = $row['id'];
$l_name = $row['l_name'];
$f_name = $row['f_name'];
$ssn = $row['ssn'];
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr>";
echo "<td class=" . $class . ">$wrap_id</td>";
echo "<td class=" . $class . ">$wrap_l_name</td>";
echo "<td class=" . $class . ">$wrap_f_name</td>";
echo "<td class=" . $class . ">$wrap_ssn</td>";
echo "</tr>";
}
echo '</table>';
mysql_close($link);
}
EDIT
To answer a few questions:
#controlfreak123, I am not sure what you mean by "include ('filename_with_php_in_it')". As far as the page not being called to be parsed, I think it is being called and contact is being made. I pointed out in my original question that I believe this is true because FireBug shows the code for the table, and that code is in separate PHP file, thus communication between the HTML file and the PHP file must be taking place. Here is how I am calling the PHP file from the HTML file you if you care to know:
<script language="javascript" type="text/javascript" src="/Management/Employee_Management.php?action=Edit_Employee"></script>
#Matt S, I am not getting much in the way of output, in fact I didn't know I was getting anything at all until I looked at FireBug and saw that the PHP code (or some of it) was indeed being passed to the HTML file. The specific question is how do I get the data I want from my MySQL database and populate it into an HTML table via PHP. I can also confirm that employees does have data in it, two entries I put in for testing. I can try to put the code into its own file without the JavaScript as you suggested, but that would defeat my purpose since I want my HTML and PHP files to be separate, but I may try it just to see if the PHP code is good and to make sure the JavaScript isn't breaking it.
#Aaron, I am not sure what you are asking (sorry). The code is meant to populate create and populate a table on an HTML page.
Here is a full example of what you're looking for:
pull some data from mysql using php
put that data into an html table
apply alternating colored rows to the table
For the styling I cheat a little and use jquery which I find a bit easier then what you're trying to do.
Also, remember $row[field] is case sensitive. So $row[id] != $row[ID].
Hope this helps:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
tr.header
{
font-weight:bold;
}
tr.alt
{
background-color: #777777;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('.striped tr:even').addClass('alt');
});
</script>
<title></title>
</head>
<body>
<?php
$server = mysql_connect("localhost","root", "");
$db = mysql_select_db("MyDatabase",$server);
$query = mysql_query("select * from employees");
?>
<table class="striped">
<tr class="header">
<td>Id</td>
<td>Name</td>
<td>Title</td>
</tr>
<?php
while ($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>".$row[ID]."</td>";
echo "<td>".$row[Name]."</td>";
echo "<td>".$row[Title]."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
Here's the table code only using PHP to alternate the styles like you're trying to do in your example:
<table class="striped">
<tr class="header">
<td>Id</td>
<td>Title</td>
<td>Date</td>
</tr>
<?php
$i = 0;
while ($row = mysql_fetch_array($query)) {
$class = ($i == 0) ? "" : "alt";
echo "<tr class=\"".$class."\">";
echo "<td>".$row[ID]."</td>";
echo "<td>".$row[Name]."</td>";
echo "<td>".$row[Title]."</td>";
echo "</tr>";
$i = ($i==0) ? 1:0;
}
?>
</table>
The reason your code is not executing is that you cannot include PHP with the Script tag. You must use PHP's include function, and the original page must be parsed as PHP.
<?php
include('./my_other_file.php');
?>
The starting of the coding is a little bit wrong. It should be:-
<?php
$query = "SELECT * FROM employees";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo '<table>';
if($num) {
while( $row = mysql_fetch_array($result) ) {
// all logic for each of the rows comes here
}
}
else {
// no rows fetched, so display proper message in a row
}
echo "</table>";
?>
The first time "mysql_fetch_array" function is used on a Resource Handler, after that it does not work properly. This answer may seem a bit vague, but I have seen it many times, so I always use a "while" or "do-while" loop for fetching multiple rows from DB.
Try using the above code, & see if any information crops up.