This question already exists:
PHP's white screen of death [duplicate]
Closed 6 years ago.
I am currently in a class at school and we have to link our MySQL database with our website using php. I already made and populated my tables in MySQL. My professor sent us this chunk of code to display the table info on our websites. However when I run it nothing happens and I haven't learned enough about php to know why it is not working. I used my correct host name, password, ect. But it won't work and when he does the tutorial online in the video it works for him.
This is the code I am using.
<html>
<head>
<title>Query All Movies from Database</title>
<body>
<?
# $db = mysql_pconnect("localhost","username","password");
if (!$db)
{
echo "ERROR: Could not connect to database. Please try again later.";
exit;
}
mysql_select_db("database name");
$query = "select * from movie";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
echo "<p>Number of movies found: ".$num_results."</p>";
for ($i=0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo "<p>";
echo htmlspecialchars( stripslashes($row["movieid"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["title"]));
echo "<br>";
//echo htmlspecialchars( stripslashes($row["directorid"]));
//echo "<br>";
echo htmlspecialchars( stripslashes($row["year"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["genre"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["runtime"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["plotdescription"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["comments"]));
echo "<br>";
echo "</p>";
}
?>
</body>
</html>
This is the output I am getting.
Directly to the screen.
Number of movies found: ".$num_results."
"; for ($i=0; $i < $num_results; $i++) { $row = mysql_fetch_array($result); echo "
"; echo htmlspecialchars( stripslashes($row["movieid"])); echo "
"; echo htmlspecialchars( stripslashes($row["title"])); echo "
"; //echo htmlspecialchars( stripslashes($row["directorid"])); //echo "
"; echo htmlspecialchars( stripslashes($row["year"])); echo "
"; echo htmlspecialchars( stripslashes($row["genre"])); echo "
"; echo htmlspecialchars( stripslashes($row["runtime"])); echo "
"; echo htmlspecialchars( stripslashes($row["plotdescription"])); echo "
"; echo htmlspecialchars( stripslashes($row["comments"])); echo "
"; echo "
"; } ?>
I did alot of research and read the links and here is the working code! Thanks for helping teach me!! This site is so great! You guys are awesome!
<?php
$servername = "localhost";
$username = "ursername";
$password = "password";
$dbname = "database name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT movieid, title, directorid, year, genre, runtime, plotdescription, comments FROM movie";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Movie ID: " . $row["movieid"]. "<br>Title: " . $row["title"]. "<br>Director ID: " . $row["directorid"]. "<br>Year: " . $row["year"]. "<br>Genre: " . $row["genre"]. "<br>Run Time: " . $row["runtime"]. "<br>Plot Description: " . $row["plotdescription"]. "<br>Comments: " . $row["comments"]." <br><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Don't use that code - that snippet is not secure these days. You should be using one of the newer connection methods like PDO or MySQLI. I prefer the latter, try using the docs on PHP's site to set up your stuff.
http://php.net/manual/en/function.mysqli-connect.php
The only reason I could imagine that your teacher is using this method is either they don't know any better or they are using a very old version of PHP.
Older MySQL functions are procedural and get wonky when writing in OOP (object oriented programming) because they are manually escaped. The newer mysqli_ functions work with both procedural and OOP and support prepared statements. Prepared statements are safer because they parameterize the values so you run into less issues with SQL injection and other vulnerabilities. You also get some speed enhancements because the prepared statements only have to parsed on the preparation and not the execution. So if you use a lot of the same parameters you get some extra speed!
PDO also supports prepared statements, but its a little more complex for newcomers because it introduces an abstraction layer (basically you build the query in PHP instead of raw SQL statements). This was a turn off for me when I first started so I would try getting good at the MySQLi stuff before you look too deep into PDO.
There are so many fundamental issues here, but it seems like the issue with your output being wrong is because you're concenating the echo string, and doing wrong. With PHP you can put variables inside of double quotes and it will still parse correctly. And as I said, the code you have posted cannot be outputting that.
So change your first echo line to this and see what happens.
echo "<p>Number of movies found: $num_results</p>";
I always say, it's far better to teach yourself something than learn from a so called professor. He has given you depreciated code, that is now removed in PHP 7. He has told you i don't know what's wrong with your code and completely steered you in the wrong direction for secure, modern web development. This professor has no business teaching anyone PHP.
Related
I am using this SQL query in a link to retrieve data from database
<div class="nav-laptop">Laptop
and display it using
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
I realized this is very vulnerable and that I should use POST method to hide parameters from URL. I tried reading online forums, but I found nothing that would help me to convert this to POST way of retrieving data.
So, how do I use POST method to achieve the same result as I am achieving right now using GET?
This will give you a general idea on how to do this.
HTML form:
<form method="post" action="your_handler.php">
<input type = "text" name = "search_query">
<input type = "submit" name = "submit" value = "Search">
</form>
SQL/PHP and assuming a successful connection using the MySQLi API.
$conn = mysqli_connect("your_host", "user", "password", "db");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if(isset($_POST['submit'])){
if(!empty($_POST['search_query'])){
$search_query = mysqli_real_escape_string($conn, $_POST['search_query']);
$result = mysqli_query($conn, "SELECT * FROM TABLE WHERE col = '$search_query' ");
if(!$result) { echo "Error: " . mysqli_error($conn); }
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// perform what you want here
// and check for errors on your query
}
}
}
}
You can substitute SELECT * with the said columns also.
Ideally, a prepared statement is nice to work with.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements (if you want to look into PDO).
Sidenote: Do not intermix different MySQL APIs such as mysqli_ with PDO. They just don't mix together.
Check for errors also against your query:
http://php.net/manual/en/mysqli.error.php
Add or die(mysqli_error($conn)) to mysqli_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure that no whitespace gets introduced into your input, otherwise your query may fail.
Use trim() against the input.
You don't need to use POST for a SELECT query. You can, but it's really better suited for INSERT / UPDATE / DELETE, things that actually change your data. A possible advantage to using a link like that for search results is that it can be saved, bookmarked, emailed, etc., where a form submission cannot. But you are right that putting your entire query into a link like that definitely is extremely vulnerable.
Instead of passing the entire query through the link, you can just pass the parameters, like this:
Laptop
Then in your display code you can use a prepared statement and safely bind the parameter:
$kategorija = $_GET['kategorija'];
$sql = 'SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi
WHERE Kategorija=? ORDER BY Proizvodac';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kategorija);
$stmt->execute();
// etc.
I'm looking to create a formatted product list from an SQL database. My aim is to have a store on my website with a series of small boxes containing some shorthand information about each product, that when clicked will open a pop-up containing detailed information. (I have a working Javascript/JQuery code to create the pop-ups.)
Here is the PHP code so far, simply to get the information from the database and display it on a webpage...
(I've been using XAMPP to provide an environment for me to test the code in)
<?php
mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("Database1") or die(mysql_error());
$strSQL = "SELECT * FROM Products";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
echo $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "<br />";
}
mysql_close();
?>
I want the echoed line to be displayed in a divider, with a divider generated for each record in the SQL database (say I have 10 products available, there would be ten dividers, and 10 different boxes on the webpage). The divider's class is "ProductBox".
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
This was the closest I have come to a solution, which was simply managing to write a code with no syntax errors - alas, nothing actually displays on the webpage.
If I'm going about this entirely the wrong way please tell me - I'm fairly sure I need to use a SQL database to dynamically update stock on a live website, but if I need to implement a different programming language or whatever then just tell me what you think would work and help me with a solution.
You have an extra semicolon in your code
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
Replace with
echo "<div class=\"ProductBox\">". $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
mysql_fetch_array needs to be used like this (see PHP Doc):
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
}
or you could just use "mysql_fetch_assoc" instead.
HOWEVER, if you're new to PHP, I HIGHLY RECOMMEND that you get started on the right foot. mysql_query functions are soon to be deprecated. DON'T USE THEM. Most recommend using "PDO" for querying your database. Here's a great tutorial to teach you: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Also, as mentioned, you have an extra semi-colon.
Dont forget these basics markups :
`<HTML>
<HEAD>
</HEAD>
<BODY> put in here your divs
</BODY>
</HTML>`
I have this table:(megaoverzicht.php) (I left out the part where it connects to the db)
echo "<table border='1'><tr><th>Formulier Id</th><th>Domeinnaam</th><th>Bedrijfsnaam</th><th>Datum</th><th>Periode</th><th>Subtotaal</th><th>Dealernaam</th><th>Offerte Maken</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['formuliernummer'] . "</td>";
echo "<td>" . $row['domeinnaam'] . "</td>";
echo "<td>" . $row['bedrijfsnaam'] . "</td>";
echo "<td>" . $row['datum'] . "</td>";
echo "<td>" . $row['periode'] . "</td>";
echo "<td> € " . $row['subtotaal'] . "</td>";
echo "<td>" . $row['dealercontactpersoon'] . "</td>";
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id).
This is the code from (offertemaken.php)(I left out the part where it connects to the db)
<?php
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
?>
<form>
<div class="formcontainer" onmousemove="">
<input type="text" name="datum" id="datum" value="<?php echo $data2[datum]?>">
<input type="text" name="formuliernummer" id="formuliernummer" value="<?php echo $data2[formuliernummer]?>">
<input type="text" name="periode" id="periode" value="<?php echo $data2[periode]?>">
<input type="text" name="domeinnaam" id="domeinnaam" value="<?php echo $data2[domeinnaam]?>">
<input type="text" name="bedrijfsnaam" id="bedrijfsnaam" value="<?php echo $data2[bedrijfsnaam]?>">
<input type="text" name="dealercontactpersoon" id="dealercontactpersoon" value="<?php echo $data2[dealercontactpersoon]?>">
</div><!--/.formcontainer-->
</form>
I cant get it to work. I am missing something I think! I make an error in the codes below:
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
I have been looking at a lot of tutorials but cant understand what i am doing wrong. Here a list to show that i am not just asking but actually have been looking for a solution by myself.
http://www.daniweb.com/web-development/php/threads/341921/-php-mysqli-update-database-using-id-syntax-help-requested-
http://www.codeofaninja.com/2012/01/phpmysqli-update-record.html
I have looked at many more but i don’t want to bother all of you with an extreme long list of links. And i am not allowed because my rep is not big enough! Dont downvote me please!
Question
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id)?
Edit 1 Getting closer to the endresult
I found out(thanks to Cuba32) that the link in megaoverzicht.php was doing nothing so i changed the following
<a href='offertemaken.php?id=" . $row->id . "'>
to
<a href='offertemaken.php?id=" . $row['id'] . "'>
Now it is creating these kind of links:
something/formulieren/overzichten/offertemaken.php?id=24
This is a good thing(i think) but the form that opens is blank so offertemaken.php is doing nothing with the id???
Edit 2 (Thanks to Cube32)
Since yesterday the code has changed quite a bit. I belive that megaoverzicht.php is finished it sends the link as described in edit 1. The only problem is know in offertemaken.php. Below i will put in the code.
$con = mysqli_connect($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,$database);
$id=$_GET['id'];
if($data = mysqli_prepare($con, 'SELECT * FROM cypg8_overzicht WHERE id="?"'))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($data, "s", $id);
/* execute query */
mysqli_stmt_execute($data);
$data2 = mysqli_stmt_fetch($data);
But this code gives me the following error.
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in line 31. Line 31:
mysqli_stmt_bind_param($data, "s", $id);
I dont know how to solve this part. I will offcourse be looking on the internet to try and find a solution but if anyone knows it please post it. Thanks in advance.
Edit 3<= No more error (Thanks to Your Common Sense)
by changing WHERE id="?"' into WHERE id=?' i no longer have the error. But still it is not showing anything in the input fields
Edit 4<= Getting to confused and going back to original code.
Thanks for everyone who got me so far. But I can't see the forest anymore through the trees. I am going back to the original code and try to solve that. So the code is now as follows:
$id=$_GET['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
error_reporting(E_ALL);
But this gives the following errors inside the input fields:
Notice: Use of undefined constant formuliernummer - assumed 'formuliernummer' in offertemaken.php on line 37
This error goes for all the input fields.
Edit 5
Fixed this by changing <?php echo $data2[formuliernummer]?> to <?php echo $data2['formuliernummer']?> but it is still not showing the information.
Edit 6 THE SOLUTION
I added the answer to the question below. Just look for answer written by HennySmafter.
Thanks to:
Cube32, SITDGNymall, Your Common Sense. Thanks all of you for helping me find the solution.
It took me a while but i found the answer.
megaoverzicht.php
echo "<td><a href='offertemaken.php?id=" . $row['id'] . "'>Offerte Maken </a></td>";
offertemaken.php
// Check whether the value for id is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen id
$result = mysqli_query($con,"SELECT * FROM cypg8_overzicht WHERE id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysqli_error($result) . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['formuliernummer'] . "\n";
echo $row['domeinnaam'] . "\n";
echo $row['bedrijfsnaam'] . "\n";
echo $row['datum'] . "\n";
echo $row['periode'] . "\n";
}
} else {
die("No valid id specified!");
}
It is not showing the values in the input boxes because there are no input boxes into the echo but those can be easily added I imagine.
In reference to the edit 1:
You are referencing the variables by association, but are outputing the mysql as a default array. instead of
$data2 = mysqli_fetch_array($query);
Try this:
$data2 = mysqli_fetch_assoc($query);
Or:
$data2 = mysqli_fetch_array($query, MYSQLI_ASSOC);
Also, do you have error reporting turned on? If so, then if the array contains no data you should be getting warnings of some kind. If not, a good test is:
error_reporting(E_ALL);
This will warn you about any places where a variable is unset or a array is empty. Another good test is to simply echo out your query, which will tell you if there's any errors in the query itself(which can save some time). If you're not going to go the Prepared Statements route(which is highly encouraged), you can simply echo out $data into your script.
This is a very noob question.
But I'm having an issue that I believe stems from this poorly written database query. I don't know if I'm not closing the connection or if closing the connection is necessary, but the server is indicating that it's timing out after about 60 seconds and it's causing a high resource usage. Could anyone tell me what's wrong with this query?
It's just a basic php query that pulls from the database.
<?php if(isset($_POST['submit'])) {
//print_r($_POST);
$example=$_POST['...'];
if ($job_number=="") { die("Nothing here.");
}
$con = mysql_connect("...","...","...");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("...", $con);
$query = "SELECT * FROM EXAMPLE WHERE job_number='$example' OR email='$example'";
$result = mysql_query($query);
if (mysql_num_rows($result) == "0") {
echo
'Nothing here.';
exit;
}
echo "<div class='sample'>";
while ($row = mysql_fetch_assoc($result)) {
//print_r($row);
//customer name
echo "<h2>" . $row['name'] ."</h2>";
//status
echo "<p>" . $row['status'] ."</p>";
}
echo "</div>";
}
mysql_close($con);
?>
To be honest there is a lot about databases you are not understanding.
Databases take time to read. The way they are indexed defines how you need to approach reading them.
Take a look at this Measuring actual MySQL query time
...and a few others.
I have a feeling your database is huge, and possibly badly structured. This is where I refer you to:
http://en.wikipedia.org/wiki/Database
There is a wealth of information here to clear your question up.
Why am I not able to echo those things like adm_no, adm_dt, etc.?
require_once("lib/connection.php");
$adm_no = $_POST['adm_no'];
if (!$adm_no == "intval") echo "You Entered wrong Admission no Recheack Admission no";
exit();
$clas = $_POST['clas'];
$query = "SELECT * FROM $clas WHERE adm_no = $adm_no";
$result = mysql_query($query);
//searchs the query in db.
while ($result1 = mysql_fetch_array($result)) {
$adm_no = $result1['adm_no'];
$adm_dt = $result1['adm_dt'];
$name = $result1['name'];
$dob = $result1['dob'];
$f_name = $result1['f_name'];
$f_office = $result1['f_office'];
$f_o_no = $result1['f_o_no'];
$m_name = $result1['m_name'];
$m_office = $result1['m_office'];
$addr = $result1['addr'];
};
echo "Admission no = ";
$adm_no;
echo " <p>Admission Date </p>";
echo " <p>Name </p>";
echo " <p>Class </p>";
echo " <p>D.O.B </p>";
echo " <p>Father s name </p>";
echo " <p>Office address </p>";
echo " <p>Office No </p>";
echo " <p>Mother s name </p>";
echo " <p>Office Address </p>";
echo " <p>Address </p>";
echo " <p>Phone no </p>";
You have a syntax error
echo "Admission no = " ;$adm_no ;
Should be
echo "Admission no = " ;
echo $adm_no ;
or
echo "Admission no = " . $adm_no ;
Well, the following does print a string and then does nothing with the variable:
echo "Admission no = " ;$adm_no ;
You where probably going for:
echo "Admission no = " . $adm_no;
Apart from that, are you aware that the print logic is only evaluated once after the while loop has iterated all the results (if more than one). That is, the variables will hold the values of the last record only.
Here is the problem your exit(); is executing every time even if the input $adm_no is okay.
Change this
if (!$adm_no=="intval")
echo "You Entered wrong Admission no Recheack Admission no" ;
exit();
to
if (!$adm_no=="intval")
{
echo "You Entered wrong Admission no Recheack Admission no" ;
exit();
}
As I told you in the previous (deleted) question, you have an SQL-injection hole.
Here's how to fix it.
Change this code:
Coding horror
$adm_no = $_POST['adm_no'];
if (!$adm_no == "intval")
echo "You Entered wrong Admission no Recheack Admission no";
exit();
$clas = $_POST['clas'];
$query = "SELECT * FROM $clas WHERE adm_no = $adm_no";
Into this code, which is not exposed to SQL-injection dangers
$adm_no = mysql_real_escape_string($_POST['adm_no']);
if (!$adm_no == "intval") {
echo "You Entered wrong Admission no Recheack Admission no"; exit();
}
$allowed_tables = array('table1', 'table2');
$clas = $_POST['clas'];
if (in_array($clas, $allowed_tables))
{
$query = "SELECT * FROM `$clas` WHERE adm_no = '$adm_no'";
}
I know that the If will only accept integers, but the if in your previous question was commented out, therefor it comes and goes, so always escape your inputs before injecting them into your query!
Note how the if in your code does not work because you forgot to enclose the body after the then in brackets {}, causing the exit(); to always be executed.
For more info on SQL-injection see: How does the SQL injection from the "Bobby Tables" XKCD comic work?
And for info on why mysql-real-escape_string or PDO doesn't work with dynamic table names
see: How to prevent SQL injection with dynamic tablenames?
And: Sample code to fix this particular SQL-injection hole
XSS hole
To fix a possible XSS hole, don't do
Coding horror
echo "Admission no = ".$adm_no;
But do this instead:
echo "Admission no = ".htmlspecialchars($adm_no);
In your case it seems that $adm_no can only hold an integer, but I don't have the table definition so I cannot be sure of that. It's best to be on the safe side and always escape dynamic output using htmlspecialchars.
See: What are the best practices for avoiding xss attacks in a PHP site
Statement 1: echo "Admission no = " ;
Statement 2: $adm_no ;
You aren't echoing the variables.
You should probably have something like:
<p>Admission no = <?php echo htmlspecialchars($adm_no); ?></p>
The way you assign the variables in the loop doesn't make any sense: if your SQL query returns more than 1 row, your code will simply replace the values. You probably want to echo the results inside the loop.
There is a syntax error here: echo "Admission no = " ;$adm_no ;.. it should be echo "Admission no = ".$adm_no;
When you are echoing the results, you are not actually echoing the variables: echo " <p>Admission Date: $adm_dt </p>";
Because echo accepts parameters as comma-separated list, like
echo $one, "two"
Using comma is also possible, but better just use heredoc syntax which support variable substitution, if you need to output large chunk of text with newlines
echo <<<HEREDOC
Your text with $variables or {$variables} here
with newlines and other nifty plaintext formatting
HEREDOC;