I run a fantasy basketball league. My php website/sql database is designed to let the person running the team do everything through the website - they can waive a player, and the player automatically goes into the FA pool, etc.
Everything has worked perfectly until about a week ago. Anytime now that a team goes to sign a player, after clicking "Sign", they get a blank PHP page. I have no idea why - I have made no adjustments to any files. It just started happening. Below is the code for the blank PHP page - can someone help?
<?php
$username = "me";
$password = "mypassword";
$database = "mydatabase";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$Team_Offering = $_POST['Team_Name'];
$Fields_Counter = $_POST['counterfields'];
$Roster_Slots = $_POST['rosterslots'];
$Healthy_Roster_Slots = $_POST['healthyrosterslots'];
$Type_Of_Action = $_POST['Action'];
$queryt="SELECT * FROM nuke_ibl_team_info WHERE team_name = '$Team_Offering' ";
$resultt=mysql_query($queryt);
$teamid=mysql_result($resultt,0,"teamid");
$Timestamp = intval(time());
// ADD TEAM TOTAL SALARY FOR THIS YEAR
$querysalary="SELECT * FROM nuke_iblplyr WHERE teamname = '$Team_Offering' AND retired = 0 ";
$results=mysql_query($querysalary);
$num=mysql_numrows($results);
$z=0;
while($z < $num)
{
$cy=mysql_result($results,$z,"cy");
$cyy = "cy$cy";
$cy2=mysql_result($results,$z,"$cyy");
$TotalSalary = $TotalSalary + $cy2;
$z++;
}
//ENT TEAM TOTAL SALARY FOR THIS YEAR
$k=0;
$Salary=0;
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
if ($Check == "on")
{
if ($Type_Of_Action == "drop")
{
if ($Roster_Slots < 4 and $TotalSalary > 7000)
{
echo "You have 12 players and are over $70 mill hard cap. Therefore you can't drop a player! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
}else{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '1000', `droptime` = '$Timestamp' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$topicid=32;
$storytitle=$Team_Offering." make waiver cuts";
$hometext="The ".$Team_Offering." cut ".$playername." to waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
} else {
if ($players_team == $teamid)
{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
} else {
if ($Healthy_Roster_Slots < 4 and $TotalSalary + $Salary > 7000)
{
echo "You have 12 or more healthy players and this signing will put you over $70. Therefore you can not make this signing. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots > 3 and $TotalSalary + $Salary > 7000 and $Salary > 103) {
echo "You are over the hard cap and therefore can only sign players who are making veteran minimum contract! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots < 1) {
echo "You have full roster of 15 players. You can't sign another player at this time! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} else {
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `bird` = '0', `cy` = '1', `cy1` = '$Salary', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
}
}
}
$k++;
}
?>
Put the following right after the open PHP tag:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
If this doesn't work, there is a probably a parse error and then you'll need to check the error log.
You will also need to escape your values that you are putting in the queries. This maybe causing a MySQL query to fail. If someone puts a " in $_POST['Team_Name'] your first query may fail.
Another final possible problem: are you sure it can still connect to MySQL?
An option to find the problem is commenting out large portions of code and then piece by piece uncommenting sectons.
Edit: So your first problem is the mysql_connect line. It needs to be changed to, notice the quotes: mysql_connect('localhost',$username,$password); Also, the variable $result and $queryt are spelt wrong in this line and used in their correct spelling: $resultt=mysql_query($queryt); I haven't checked the rest, but there maybe other errors that will cause your script to break. Some of the errors list are important to fix, but won't break your script.
Escaping: Check out the following page: http://php.net/manual/en/function.mysql-escape-string.php This basically prevents people from deleting your entire database.
Check the sample code on this page to find out how to connect to MySQL and check to see if you are connected.
Another suggestion: Are you sure none of your queries are failing? You probably want to check if the result from query is false before continuing, like:
if ($resultcat2 === false) {
trigger_error('query failed ' . $sql, E_USER_ERROR);
echo 'Sorry, there was a problem processing your request. Please try again later.';
exit;
}
Turn error reporting on for PHP in your php.ini file and see if any errors or warnings are reported. Also try removing the trailing whitespace at the end of the file before the last ?>, this has caused problems for me in the past.
Added comments to some of the above responses. Please try to dumb down for me as much as possible - I'm extremely new to this. I can't figure out why it would suddenly stop working, though, when I've made no changes at all to the code.
If you made no changes to any files and it just "broke" then that would indicate that either your webhost went thru a configuration change, your database got hosed somehow, or that someone else may've changed something.
To help spot the culprit, after every one of these
if{
else{
while{
or/and after every few statements (statements end with a semicolon ;) add this to the next line
print "<br> made it to this label: some_unique_label_name_here";
Where you should replace the label each time to help you trace the code.
This will be your first step into debugging the script to figure out how far the code execution is reaching.
Without going through your code in too much detail,I would suggest you look for any sections that may loop for a long time,without returning
After enabling error reporting, make sure to put in else statements that correspond with all of your if-statements so you can determine if those statements are being triggered or not. Throw in some echos.
Also, to clarify - I have probably three dozen PHP files on the site - this is the ONLY one that has stopped working.
As an aside, you should change every variable from a get or post such as:
$Team_Offering = $_POST['Team_Name'];
to
$Team_Offering = mysql_real_escape_string($_POST['Team_Name']);
before using it in a mysql query, otherwise you are vunerable to SQL injection attacks.
This is where I got...everything below the print line wouldn't show up if I put the print line below it.
$k=0;
$Salary=0;
print "<br> made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
So an update...nothing. lol
If you review this code:
$k=0;
$Salary=0;
print " made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
If I put the print statement below while, the page goes blank and it doesn't show up. If the print statement is before while, the statement shows up but there's no action made on the page. The end result is that when running this page, the player selected on the previous page should be removed from Free Agents, added to the user's team, and a story should be posted on the front page announcing it. Obviously none of those are happening here.
Related
I am a very novice programmer and am just beginning to use php.
I am using php to get the user ip store it in mysql. try inserting the ip to the mysql db. if it is already there then update the visit count. But none of my queries are working. It is returning that I am connected to my db
This is what i have so far:
$ipaddress = $_SERVER["REMOTE_ADDR"];
print "$ipaddress <br>";
$rv = mysqli_real_query("INSERT INTO visit ( ipaddress, count) VALUES ( '$ipaddress', 1)");
if ($rv === false){
mysqli_real_query($con,"UPDATE visit SET count=count+1
WHERE ipaddress = '$ipaddress'");
mysqli_close($con);
}
mysqli_close($rv);
$count = mysqli_real_query("SELECT count from visit where ipaddress = '$ipaddress'");
print "You have visited this site $count time(s)";
1.) Where's your $con for your first query in $rv?
2.) Your queries need backticks for reserved words such as count:
$rv = mysqli_real_query($con, "INSERT INTO `visit`(`ipaddress`, `count`) VALUES('$ipaddress', 1)");
3.) Your inside if statement will only fire if there is an error in your first line. This means you'll never actually UPDATE the count, unless something went wrong.
Suggestion 1: - Open up your table in phpmyadmin and insert a row in manually with your IP address and some random count number. Then work on being able to display the line You have visited this site x time(s). Once that is working, then work on inserting/updating your table.
Suggestion 2: You should do it the other way around. That is, check to see if the ip address exists in the table. If it does - update it. If it doesn't exist, then add a new row.
This is fine for practicing simple database connections, but a better way to do this would be to write a simple file to a /tmp/ folder and append 1 character. A single ASCII character is 1 byte, so the number of visits is simply the filesize of that ip file in bytes. Appending a single character and running a filesize check should have a lot less overhead than running database queries.
Example:
//Logging a Visit
$log_file = '/tmp/ip_'.$_SERVER['REMOTE_ADDR'];
$log = fopen($log_file, "a");
fwrite($log,'0');
fclose($log);
//Displaying Count
if(file_exists($log_file)){
$visits = filesize($log_file);
echo $log_file.' has visited the site '.$visits.' time'.($visits>1 ? 's':'');
}
else{
echo $log_file.' has not previously visited the site';
}
See here for an example of how I suggested this method to another user to block a bot that visited a site more than x number of allowed times: Number of page requests by any Bot in 5 secs
Also, just remember that with routers and NAT, an ip address does not guarantee a unique visitor, so IP address should not be relied on to identify a unique user in most situations.
Some problems:
You aren't escaping your SQL statement.
You close your connection (twice), and then never open it again when you are executing the SELECT statement.
You are not escaping your query arguments.
Fixing these issues, results in the following:
<?php
$con = mysqli_connect();
$ip = mysqli_real_escape_string($_SERVER["REMOTE_ADDR"]);
$q = 'INSERT INTO `visit` (`ipaddress`, `count`)';
$q .= 'VALUES ("'.$ip.'",1) ON DUPLICATE KEY UPDATE `count` = `count` + 1';
$result = mysqli_real_query($q);
if (!$result) {
echo mysqli_error();
}
$q = 'SELECT `count` FROM `visit` WHERE `ipaddress` = "'.$ip.'"';
$result = mysqli_real_query($q);
if (!$result) {
echo mysqli_error();
} else {
print "You have visited this site ".$result[0]."time(s)";
}
?>
I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.
I'm trying to implement a two-step registration form for my site wherein I used 2 separate pages in order to get the information from the user.
First Step:
if($submit)
{
$connect = mysql_connect("localhost","root","");
mysql_select_db("mydb");
$queryreg = mysql_query("INSERT INTO volunteerbio VALUES (<my insert values>)");
}
//gets the latest id added
$query = mysql_query("SELECT MAX(volunteerID) FROM volunteerbio");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while($row = mysql_fetch_assoc($query))
{
$dbaccountID = $row['volunteerID'];
}
header("Location: http://localhost/RedCrossCaloocan/registration2_volunteer.php");
$_SESSION['volunteerID']=$dbaccountID;
}
}
?>
What the first step does is that it creates a complete table row wherein the values needed for the second step will be temporarily left with blank values until they are updated in the next step.
Second Step:
<?php
session_start();
$idnum = #$_SESSION['volunteerID'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mydb");
if($submit)
{
$updateSkills = mysql_query("
UPDATE volunteerbio
SET medicalSkillRating = $medicalRating,
electronicsSkillRating = $electronicRating,
errandSkillRating = $errandRating,
childCareSkillRating = $childCareRating,
counsellingSkillRating = $counsellingRating,
officeSkillRating = $officeRating,
communicationSkillRating =$communicationRating,
carpentrySkillRating = $carpentryRating
WHERE volunteerID = $idnum;
");
}
?>
The second step basically updates the fields which where filled with blank values during the first step in order to complete the registration.
The first step already works and is able to add the values to the database however, I am having a problem on updating the blank values through the second step.
I have a feeling that there may be a problem regarding my usage of sessions in order to get the newly generated ID from the first step, but I just can't figure it out.
You are doing:
header("Location: http://localhost/RedCrossCaloocan/registration2_volunteer.php");
$_SESSION['volunteerID']=$dbaccountID;
The second line MAY never get executed, because you do a redirect before it. I say MAY because it MAY get executed. You have to add exit(); after all redirects to prevent further execution of the script.
Another thing:
Never suppress warnings in PHP using #. The # is almost never needed. So instead of doing:
#$_SESSION['volunteerID'];
You should do:
if (isset($_SESSION['volunteerID'])) {
$idnum = $_SESSION['volunteerID'];
} else {
// something went wrong???
}
I can't see it in your example, but do prevent SQLi vulnerabilities?
I wrote a PHP script to push notifications using APNS. I added a PHP progress bar to monitor how many users that have been pushed. The progress bar is displayed in the PHP page. I also keep updating a MySOL database to record the number. This script is expected to run a very long time. After running for about 3 hours, the PHP page (with progress bar) is stopped, but when I check the database, the number of pushed users is still increasing. This means the script is still running in server's memory, but why has the page display stopped?
here is some code:
$count = 1;
while($row = mysql_fetch_array( $result )) {
$pushToken = $row['pushToken'];
$result2 = mysql_query("SELECT COUNT(*) FROM deactivated_pushtokens WHERE pushToken LIKE '$pushToken'");
list($token_deactivated) = mysql_fetch_row($result2);
if ($token_deactivated==0){
if ($row['pushToken']!=""){
if (strlen($row['pushToken']) == 64){//All valid push tokens will have a 32x2=64 length
//echo "<br>$count. Sending push to ".$row['deviceID']." Device token = ".$row['pushToken'];
//echo "<br><br>";
if($count > $sendThreshold)
{
$pushMessage->sendMessage($row['pushToken'],$count,$appVersion,$mode,$message, $push_id);
}
if($count >= $push_update_count * $push_update_interval)
{
$pushlog_update = mysql_query("UPDATE pushlogs SET num_push_sent = '".$count."' WHERE push_id = '".$push_id."'");
if(!$pushlog_update)
{
// echo "pushlog table update error: ".mysql_error."<br />";
}
/* if($count<=$maxBar) // if failed again commment out and use block bleow
{
$prb->moveStep($count);
}
*/
$push_update_count++;
}
if($count >= $update_progressbar_count * $update_progressbar_interval)
{
if($count<=$maxBar)
{
$prb->moveStep($count);
}
$update_progressbar_interval++;
}
$count++;
// move the Bar
Perhaps the page display stopped due to the configuration of apache in httpd.conf
KeepAliveTimeout 300
PHP still running due to the property max_execution_time on php.ini
Just to notice, you are not calling the mysql_error function at all, replace the line:
echo "pushlog table update error: ".mysql_error."";
with this one:
echo "pushlog table update error: ".mysql_error()."<br />";
Further more, what you are doing is very bad practice. Try making an updater, keep you position into a session, and update/refresh the page and continue from where you left the execution. And if you do not have a tim_out limit in your .htaccess doesn't mean anything. And sometimes you might just not set the time limit.
Try refreshing page first, to see if it helps you. You can use a html meta tag for that. or:
header('Location: thispage.php');
And make each step of you program into a request.
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.