Basic connect to database, run query, close connection? - php

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.

Related

PHP calling MySQL [duplicate]

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.

Recalling random values from mysql table

I'm fairly new to php and mysql and I'm on the home stretch of finishing my page but I've been banging my head on the keyboard all day trying to figure out how to fix this problem. I've set up a php script to run as a cron even every 24 hours. The script assigns a random number between 10 and 30 to each field in my table. That works fine and every time I load the script the values change.
The problem I'm having is when I try to use those values. The result keeps printing as the word Array instead of the number in the table. So I'll give you some snippets of the code I'm running here. This is the cron event.
?php
$con = mysql_connect("localhost","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$random= rand(10, 30);
mysql_query("UPDATE winners SET pool= '$random'");
mysql_close($con);
And here is the script to call up the values.
php?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
I've tried every possible variation I can think of to this code but all I can get is it to echo either Array or Resource #9. Any insight into this would be greatly appreciated.
You do not want to echo the content of $row, which contains all data returned for the current line you've fetched from the database when calling mysql_fetch_array().
Instead, you want to access the content of $row's pool item :
echo $row['pool'];
You should probably take a closer look at the manual page for mysql_fetch_array(), and the examples it contains.
Note that you'll probably also want to modify the condition in the following line :
if ( $row % 2 )
You probably don't want the test to be done on $row, but on an item it contains.
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row['pool']";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
}
Hope this helps.

Is this PHP/MySQL delete function secure?

I have a setup where I am deleting entries from a table.
It is based on the querystring of the URL which I'm thinking might be a bad way to start anyway.
So if the URL is:
http://www.example.com/delete.php?id=123&ref=abc
And the php in delete.php is as follows:
$id=$_GET['id'];
$ref=$_GET['ref'];
$con = mysql_connect("blahblah","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
mysql_query("DELETE FROM mytable WHERE id=" . $id . " AND ref='" . $ref . "'");
mysql_close($con);
Is there a way to make this more secure... or is this indeed in any way secure at all??
EDIT:
OK, so based on the feedback I've taken a new approach.
list.php contains a set of radiobuttons for each entry in the table - as follows:
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM myTable");
echo "<form name='wer' id='wer' action='delete.php' method='post' >";
echo "<table border='1'>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td><input type='radio' name='test1' value='" . $row['id'] . "' /></td>";
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='submit' value='Submit' />";
echo "</form>";
mysql_close($con);
And delete.php looks like this:
function check_input($value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
$con = mysql_connect("localhost","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$varID = check_input($_POST["id"]);
mysql_select_db("db", $con);
$sql="DELETE FROM myTable WHERE id IN (" . $varID . ")";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
header("Location: list.php");
Is this a better way to go about it?
You have a SQL injection vulnerability since you don't sanitize the GET parameters you put into your query. The attacker can use that to delete all elements in your table.
The clean solution to this is using prepared Statements.
The quick and dirty solution is putting them in quotation marks and running them through mysql_real_escape_string.
Even if you fix that part, if the attacker can guess a valid id/ref pair he can delete that entry.
If a parameter is an integer, then why don't you make its type integer too? Something like $id=intval($_GET['id'])
GET is considered a safe method and should not have any side effects:
In particular, the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".
In your case your script might be vulnerable to Cross-Site Request Forgery. You should better use POST instead and consider some kind of authentication and authorization check before deleting.
Additionally, since you use the passed parameters unaudited and unmodified, you are also vulnerable to SQL Injections.
At the very least, you should put these values into parameters instead of sticking them right into your SQL statement. Right now you are vulnerable to a SQL Injection attack. Here is a good article on how to parameterize your query, use a stored procedure, or validate the incoming statement. This should greatly help your security:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
mysql_query(sprintf("DELETE FROM mytable WHERE id='%s' AND ref='%s'", mysql_real_escape_string($id),mysql_real_escape_string($res)));

How to Make a table field return as a link (from a simple echo command)

I've been trying for hours to figure out how to put a link into the following text output via PHP echo(). I basically want to make the title field I'm pulling from my events table (as seen in #4 in the code below) to come back into the browser as a link instead of just text...
the original code that brings back the event title:
<?php
// 3. Perform database Query to bring list of events
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned Data
while ($row = mysql_fetch_array($result)) {
echo $row ["eventtitle"]."<br/>".$row["eventdesc"]."<br/>";
}
?>
How would I go about getting that $row["eventtitle"] to appear in the browser as a link? Let's say if the link was just "eventprofile.php". This is probably an easy fix, but I've been getting a million errors with trying different things with <a href>s.
<?php
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo "".$row["eventtitle"]."<br/>".$row["eventdesc"]."<br/>";
}
?>
add an anchor tag for it!!
echo "" . $row['eventtitle'] . '' . "<br />" .$row["eventdesc"]."<br/>";
And thats it.

Running an If/Else PHP function with SQL

Thank you for reading my question.
I am trying to make a site where information from a database is displayed onto a webpage. The end result will look like this, but for a different game.
Here is a plain HTML page of what I want it to look like.
So far I know that my connection to the database works. When I run:
mysql_select_db("DATABASE", $con);
$result = mysql_query("SELECT * FROM DATABASE");
while($row = mysql_fetch_array($result)) {
echo $row['Title'] . " " . $row['Type'];
echo "<br />";
}
It returns the Title and Type.
What I want to do is run an If/Else statement that runs a different that block of code depending on the card type.
while($row = mysql_fetch_array($result)) {
if ($row['Title'] == 'Hero') {
echo "<div>";
}
}
I tried this based on the tutorials at w3schools.com but it doesn't work.
Do any of you have any ideas for what I should do?
EDIT:
Here is what I tried running:
while($row = mysql_fetch_assoc($result)) {
if ($row['Title'] == 'Hero') {
echo $row['Title'] . " Hero.<br>";
} else {
echo $row['Title'] . " Who cares.<br>";
}
}
Here is the output (Gimli should show up as a Hero):
For Gondor! Who cares.<br>
Bilbo Baggins Who cares.<br>
Ungoliant's Spwan Who cares.<br>
Gimli Who cares.
EDIT 2: Thank you Phil for spotting the error, I now get the result I wanted using Mikushi's method. Thank you all so much.
The fetching of your mysql result seems wrong, should be like this:
while($row = mysql_fetch_assoc($result)) {
if ($row['Title'] == 'Hero') {
echo ""; }
}
mysql_fetch_array fetch the result as an indexed array (1=> data, 2=> thing) , which explains why $row['Title'] doesn't work.
The difference:
http://ca2.php.net/mysql_fetch_array
http://ca2.php.net/mysql_fetch_assoc
Please, always refer to the documentation, it's very well done and a better source than w3cschools.
Maybe it's one of those all too obvious things but...
Shouldn't it be
if ($row['Type'] == 'Hero') // "Type", not "Title"

Categories