php registration mysql not a valid resource - php

Ok help..my registration page worked on the local server but its now saying that the two mysql lines are not valid when its online..why does it change when it goes online? the code pasted is all thats relevant. for some reason it doesnt like the transaction..and the email check mysql bit
include 'Connect.php'; //Connects to database
//When form is submit:-
if(isset($_POST['submit']))
{
// On submit, retrieve table values for php.
$Firstname = mysql_real_escape_string($_POST['firstname']);
$Surname = mysql_real_escape_string($_POST['surname']);
$Password = mysql_real_escape_string($_POST['password']);
$PasswordCheck = mysql_real_escape_string($_POST['passwordcheck']);
$Email = mysql_real_escape_string($_POST['email']);
$EmailCheck = mysql_real_escape_string($_POST['emailcheck']);
//CHECKS.
//Check username is available by retrieving any same values from the DB table.
$CheckEmailAvailable = mysql_query("SELECT * FROM 'user_details' WHERE Email = '$Email'");
echo $CheckEmailAvailable;
// $result = mysql_query("SELECT * FROM $tbl WHERE Email='$email' and LoginPassword='$password'");
$Results = mysql_fetch_array($CheckEmailAvailable);
//If Username field is blank.
if($Email == null )
{
echo "You must enter an email address.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If RESULTS is any value other than NULL, die.
if($Results != null )
{
echo "Email already taken. Please try another.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Password and PasswordCheck fields in reg do not match, die.
if($Password != $PasswordCheck)
{
echo "The passwords you have entered do not match. Please try again.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Password field is NULL (i.e. blank) die.
if($Password == Null)
{
echo "Your password must not be blank.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Email and EmailCheck are not equal, die.
if($Email != $EmailCheck)
{
echo "The email addresses you have entered do not match. Please try again.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//ELSE add data to DB.
else
{
//BEGIN TRANS
mysql_query("BEGIN TRAN");
//TABLE ADD.
$sql=mysql_query("INSERT INTO `user_details` (`Firstname`, `Surname`, `Email`, `Password`) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
or mysql_query("ROLLBACK TRAN") . die(mysql_error("Error registering, the database may be down, please try again later."));
//COMMIT transaction, to ensure data is added properly.
mysql_query("COMMIT TRAN");
header( 'Location: RegSucc.php' ) ;
}
} ?>
<html>
<!--Registration Form-->
<form name="form1" method="post" style="margin-left: 28%" action="Register.php">
<table width="100%" border="0" cellpadding="3" cellspacing="1">
<tr>
<td colspan="3"><strong>Register Account</strong></td>
</tr>
<tr>
<td style="width: 83px">First Name:</td>
<td>:</td>
<td><input name="firstname" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Surname:</td>
<td>:</td>
<td><input name="surname" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Email Address:</td>
<td>:</td>
<td><input name="email" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Email Address Confirmation:</td>
<td>:</td>
<td><input name="emailcheck" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Password:</td>
<td>:</td>
<td><input name="password" type="password"/></td>
</tr>
<tr>
<td style="width: 83px">Verify Password:</td>
<td>:</td>
<td><input name="passwordcheck" type="password"/></td>
</tr>
<tr>
<td style="width: 83px"> </td>
<td> </td>
<td><input type="submit" name="submit" value="Register"/></td>
</tr>
</table>
</form>

The query
SELECT * FROM 'user_details' WHERE Email = '$Email'
Is invalid. When denoting table names, it is good practice to use backticks, but using quotes will not work!
SELECT * FROM `user_details` WHERE Email = '$Email'
On your localhost, it may be setup to work with quotes. However, that is not the way it is "supposed" to be, and the server's installation may be different. Moral of the story: don't take shortcuts or use ugly code. Don't forget to backtick table names or columns, don't use PHP shorttags, etc.

$sql=mysql_query("INSERT INTO `user_details` (`Firstname`, `Surname`, `Email`, `Password`) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
should be
$sql=mysql_query("INSERT INTO user_details (Firstname, Surname, Email, Password) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
Also
SELECT * FROM 'user_details' WHERE Email = '$Email'
should be
SELECT * FROM user_details WHERE Email = '$Email'
that's it...

Change this line
$CheckEmailAvailable = mysql_query("SELECT * FROM 'user_details' WHERE Email = '$Email'");
to
$CheckEmailAvailable = mysql_query("SELECT * FROM user_details WHERE Email = '".$Email."'");
The problem is that when you moved to another server online (I can guess you were developing on Windows[which is case insensitive in MySQL], and your online server is Linux[case sensitive in MySQL]
If your string contains a variable to be evaluated and parsed, the use of single quotes around that variable name, within the double quote containing that string, is not so reliable most times. The best approach, (from personal experiences) is to do a concatenation.

Related

having problems making a program with PHP

I created two forms, one is registration form the other is picking the dates the user will come and leave. I called the user's username in the 2nd page.. and although i receive it, i get a message "error" and nothing gets updated on my database. Here is my 2nd page file.. What am i doing wrong?
<?php
session_start();
$EntryError=$ExitError="";
if (isset($_POST['submit'])){
$entrydate = $exitdate = "";
$errorOccured = false;
if (isset($_POST['tsmdate'])){
$entrydate = trim($_POST['tsmdate']);
if (strlen($entrydate) == 0){
$EntryError = "date is missing";
$errorOccured = true;
}
}
else{
$EntryError = "date is missing";
}
// checking for last name
if (isset($_POST['tsmexit'])){
$exitdate = trim($_POST['tsmexit']);
if (strlen($exitdate) == 0){
$ExitError = "First Name is missing";
$errorOccured = true;
}
}
else{
$ExitError = "last Name is missing";
}
$ids=$_SESSION['tsmUserName'];
var_dump($_SESSION);
if(!$errorOccured){
require_once("connection.php");
$my_query="INSERT INTO timing (No, Entry Date and Time, Exit Date and Time, user_id) VALUES (NULL,'$EntryError','$exitdate','$ids')";
$result=mysqli_query($connection,$my_query);
if($result)
{
echo 'thank you';
}
else
{
echo 'error';
}
mysqli_close($connection);
}
}
?>
<html>
<head>
</head>
<body>
<form name="dates" id="dates" method="POST" action="">
<table cellpadding="5" border="0" width="100%">
<tr>
<td colspan="3" align="center">
<h1> select dates </h1>
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmdate">Entry date and time</label>
</td>
<td align="left">
<input type="text" name="tsmdate" id="tsmdate" required="required">
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmexit">Exit date and time</label>
</td>
<td align="left">
<input type="text" name="tsmexit" id="tsmexit" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="dates">
</td>
</tr>
</table>
</form>
</body>
</html>
Change INSERT query to this
$my_query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL,'$EntryError','$exitdate','$ids')";
Make sure if any database field name has space in name, then it should be within ` (back tic)
Your insert query isn't a valid query because of the spaces in your column names, I suggest your change the spaces into '_' characters so you won't walk into more trouble. If you like to keep the spaces you have to escape the column names with the "`" character.
Example
$query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL, '$EntryError', '$exitdate', '$ids')";
Your form is very vulnerable to SQL injection, to prevent this you have to escape your variables with the mysqli::real_escape_string function.
Example
$EntryError = mysqli_real_escape_string($connection, $EntryError);
$exitdate = mysqli_real_escape_string($connection, $exitdate);
$query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL, '$EntryError', '$exitdate', '$ids')";

PHP/MySQL allowing current user to edit their account information

I have created 2 pages
update.php
edit.php
We start on edit.php so here is edit.php's script
<?php
session_start();
$id = $_SESSION["id"];
$username = $_POST["username"];
$fname = $_POST["fname"];
$password = $_POST["password"];
$email = $_POST["email"];
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("a2670376_Pass") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE members SET username = '$username', fname = '$fname',
password = '$password' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
<form action="update.php" method="post">
<input type="hidden" name="id" value="<?=$id;?>">
ScreenName:<br> <input type='text' name='username' id='username' maxlength='25' style='width:247px' name="username" value="<?=$username;?>"/><br>
FullName:<br> <input type='text' name='fname' id='fname' maxlength='20' style='width:248px' name="ud_img" value="<?=$fname;?>"/><br>
Email:<br> <input type='text' name='email' id='email' maxlength='50' style='width:250px' name="ud_img" value="<?=$email;?>"/><br>
Password:<br> <input type='text' name='password' id='password' maxlength='25' style='width:251px' value="<?=$password;?>"/><br>
<input type="Submit">
</form>
Now here is the update.php page where I am having the major problem
<?php
session_start();
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
mysql_select_db("a2670376_Pass") or die(mysql_error());
$id = (int)$_SESSION["id"];
$username = mysql_real_escape_string($_POST["username"]);
$fname = mysql_real_escape_string($_POST["fname"]);
$email = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
$query="UPDATE members
SET username = '$username', fname = '$fname', email = '$email', password = '$password'
WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
Now on edit.php I fill out the form to edit the account "test" while I am logged into it now once the form if filled out I click on Submit button
and it takes me to update.php and it returns this
(0) Not Updated
(0) <= id of user logged in
Not Updated <= MySql Error from
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
I want it to update the user logged in and if I am not mistaken in this script it says
$id = (int)$_SESSION["id"];
which updates the user with the id of the person who is logged in
but it isn't updating, its saying that no tables were effected
if it helps here's my MySQL Database picture
just click here http://i50.tinypic.com/21juqfq.png
if this could possibly be any help to find the solution I have 2 more files delete.php and delete_ac.php they have can remove users from my sql database and they show the user id and it works there are no bugs in this script at all PLEASE DO NOT MAKE SUGGESTIONS FOR THE SCRIPTS BELOW
delete.php first
<?php
$host="mysql13.000webhost.com"; // Host name
$username="a2670376_Users"; // Mysql username
$password="PASSWORD"; // Mysql password
$db_name="a2670376_Pass"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// select record from mysql
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<table border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td colspan="8" style="bgcolor: #FFFFFF"><strong><img src="http://i47.tinypic.com/u6ihk.png" height="30" widht="30">Delete data in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>UserName</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>FullName</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Password</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Date</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Ip</strong></td>
<td align="center" bgcolor="#FFFFFF"> </td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['username']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['fname']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['password']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['date']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['ip']; ?></td>
<td bgcolor="#FFFFFF">delete</td>
</tr>
<?php
// close while loop
}
?>
</table>
<?php
// close connection;
sql_close();
?>
and now delete_ac.php
<table width="500" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td colspan="8" bgcolor="#FFFFFF"><strong><img src="http://t2.gstatic.com/images? q=tbn:ANd9GcS_kwpNSSt3UuBHxq5zhkJQAlPnaXyePaw07R652f4StmvIQAAf6g" height="30" widht="30">Removal Of Account</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">
<?php
$host="mysql13.000webhost.com"; // Host name
$username="a2670376_Users"; // Mysql username
$password="javascript00"; // Mysql password
$db_name="a2670376_Pass"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
// if successfully deleted
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='delete.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
</td>
</tr>
</table>
Try below query, and post output here. Also execute same echo query in phpmyadmin to see what happend.
echo $query="UPDATE members
SET username = '$username', fname = '$fname', email = '$email', password = '$password'
WHERE id=$id";
From your link it seems anyone can directly go to edit page, that is wrong.
You need to add condition that if user is login then only he can update his profile.
Could you check on edit.php if $id is actually set to some value instead of empty? Might be that the id is never stored in the session
Right now your $id is null. (int)$id is 0.
So when you try to update WHERE id=$id you are basically saying WHERE id=0
If id is an Auto Increment Integer then you are not going to have an id=0 and nothing will be updated. You need to create the $_SESSION['id'] by putting something in it.
$_SESSION['id'] = XXXX;
$sqlshow =# mysqli_query($con,"SELECT `id`, `Registration_No`, `First_Name`, `Middle_Name`, `Sir_Name`, `Sex`, `Birth_Day`, `Email`, `Address`, `Phone` FROM `cdtistudent` WHERE id=40"); while($row = #mysqli_fetch_object($sqlshow)) {
update.php page
if(isset($_POST["update"])){
$Registration = $_POST['Registration'];
$First_Name = $_POST['First'];
$Middle_Name = $_POST['Middle'];
$Sir_Name = $_POST['Sir'];
$Sex = $_POST['Sex'];
$Birth_Day = $_POST['Birth'];
$Email = $_POST['Email'];
$Address = $_POST['Address'];
$Phone=$_POST['Phone'];
$id=$_POST['id'];
$sqlupdate =mysqli_query($con,"UPDATE cdtistudent
SET
Registration_No='$Registration',
First_Name='$First_Name',
Middle_Name='$Middle_Name',
Sir_Name='$Sir_Name',
Sex='$Sex',
Birth_Day='$Birth_Day',
Email='$Email',
Address='$Address',
Phone='$Phone'
WHERE id='$id'");
if($sqlupdate === false){
die("".mysqli_error($con));
}}
it look like
UPDATE cdtistudent SET id=[value-1],Registration_No=[value-2],First_Name=[value-3],Middle_Name=[value-4],Sir_Name=[value-5],Sex=[value-6],Birth_Day=[value-7],Email=[value-8],Address=[value-9],Phone=[value-10] WHERE id=?;
and edit.php page
$sqlshow =# mysqli_query($con,"SELECT `id`, `Registration_No`, `First_Name`, `Middle_Name`, `Sir_Name`, `Sex`, `Birth_Day`, `Email`, `Address`, `Phone` FROM `cdtistudent`
WHERE id=40");
while($row = #mysqli_fetch_object($sqlshow))
{

Error passing variables using a form php>form>php

Please whats wrong with this code?
Im using it to add some data to database but im getting empty $toid and $toname when trying to insert.
This is the form. The variables $toid and $toname are ok here.
//write new message
if (isset($_GET['action']) && $_GET['action'] == compose) {
if (isset($_GET['toid'])) {
$toid = $_GET['toid'];
$tosql = "select * from authors where id =".$toid."";
$toquery = mysql_query($tosql,$connection) or die(mysql_error());
$torow = mysql_fetch_array($toquery);
$toname = $torow['displayname'];
if (isset($_GET['subject'])) { $subject = $_GET['subject']; }
if (isset($_GET['message'])) {
$message = $_GET['message'];
echo "<h3>Replying</h3>
<table>
<tr>
<td colspan='2'>Replying to ".$toname.".</td>
</tr>
<tr>
<td colspan='2'>".$subject."".nl2br($message)."<br />
</td>
</tr>
</table><br />Type your answer:<br /><br />";
} else { echo "New message"; }
echo "<form action=\"mail.php?action=send\" method=post>
<table>
<tr>
<td>To:</td><td><input type=\"text\" name=\"to\" size=\"50\" value=\"".$toname."\"></td>
</tr>
<tr>
<td>Title:</td><td><input type=text name=subject size=50 value=".$subject."></td>
</tr>
<tr>
<td valign=\"top\">Message:</td><td><textarea rows=\"10\" cols=\"70\" name=\"message\"></textarea></td>
</tr>
<tr>
<td align=\"right\" colspan=\"2\"><input id=\"submitstyle\" type=\"submit\" value=\"Enviar Mensagem\"></td>
</tr>
</table>
</form>";
}
}
Here is the code to insert the message to databse, the $toid and $toname are empty here. Its suposed to being retrieved from the form above, right?
//send message
if (isset($_GET['action']) && $_GET['action'] == send) {
if ($subject == "" || $message == "") {
header('Location: mail.php?action=compose&toid='.$toid.'&subject=\''.$subject.'\'&sendpm=false');
exit();
}
$date = DATE(YmdHis);
echo $userid."from<br />to".$toid."<br />toname".$toname;
$sendsql = "INSERT INTO mail (sender, reciever, subject, message, created_at, status, sender_deleted, reciever_deleted)
VALUES (".$userid.", ".$toid.", ".$subject.", ".$message.", ".$date.",unread, 0, 0)";
$sendquery = mysql_query($sendsql,$connection) or die(mysql_error());
echo "<div class=\"alert\" style=\"text-align: center; margin-top: 13px;\"><b>Mensagem particular enviada com sucesso!</b></div>
<br /><table align=\"center\" width=\"75%\" class=\"sortable\">
<tr>
<td colspan='2' style=\"text-align:center;font-weight:normal;\">Mensagem particular enviada para ".$toname.".</td>
</tr>
<tr>
<td colspan='2'>
Title: ".$subject."
Message: ".nl2br($message)."
</td>
</tr>
</table>";
}
Im also getting this sql error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' RE: assunto3, 3, 20121017023723,unread, 0, 0)' at line 2 wich i think its because of the empty variables mentioned.
First, you need to pass those variables as hidden form values: http://www.echoecho.com/htmlforms07.htm
Then you need to get the variables from the form via $_POST.
Try $toid = $_POST['toid'] and $toname = $_POST['toname']. But be wary about SQL injection: http://php.net/manual/en/security.database.sql-injection.php
Don't just accept values blindly from $_POST. Be sure to validate and filter them first.
Or if toid/toname aren't changable by the user, why not just requery for them?
You need to escape the INSERT values, and put strings in quotes:
$sendsql = 'INSERT INTO mail (sender, reciever, subject, message, created_at, status, sender_deleted, reciever_deleted)
VALUES ("'.mysql_real_escape_string($userid).'", "'.mysql_real_escape_string($toid).'", "'.mysql_real_escape_string($subject).'", "'.mysql_real_escape_string($message).'", "'.mysql_real_escape_string($date).'","unread", 0, 0)';
Also, be sure you always escape the values that are immediately used in SQL queries from $_GET or $_POST. Otherwise, you are most likely to experience SQL injection
You need to write SQL Statement in php like that:
$tosql = "select * from authors where id ='$toid'";
and
$sendsql = "INSERT INTO mail (sender, reciever, subject, message, created_at, status, sender_deleted, reciever_deleted)
VALUES ('$userid', '$toid', '$subject', '$message', '$date', 'unread', 0, 0)";
i think this will be help you.

Registration form not submitting and drop down box not populating

I'm working on a registration form for my website.
One of the fields on my registration form is a drop down box that is populated by a table on my MySQL database.
I originally wrote the registration script a different way but I needed to change how the form worked to accommodate the new drop down box and the way it gathered its data.
Before the changes the form was successfully submitted, but now it just gives me a white screen.
I have checked the mysqli_connect.php with an if-else statement. It showed that it was working but no registrations were being sent to the MySQL server when the submit button was pressed. Also, the drop down box was not showing any of the content from the MySQL table that it was linked to.
Below is a copy of the script that I am using:
<?php
#ini_set('display_errors', 'on');
echo "<h1>Register</h1>";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$errors = array();
if (empty($_POST['firstname'])){
$errors[] = 'Your forgot to enter your first name.';
}else{
$firstname = trim($_POST['firstname']);
}
if (empty($_POST['lastname'])){
$errors[] = 'Your forgot to enter your last name.';
}else{
$lastname = trim($_POST['lastname']);
}
if (empty($_POST['username'])){
$errors[] = 'Your forgot to enter your username.';
}else{
$username = trim($_POST['username']);
}
if (!empty($_POST['password1'])) {
if ($_POST['password1'] != $_POST ['password2']) {
$errors[] = 'Your password did not match the confirmed password!';
}else{
$password = trim($_POST['password1']);
}
} else {
$errors[] = 'You forgot to enter your password!';
}
if (empty($_POST['birthdate'])){
$errors[] = 'Your forgot to enter your birthdate.';
}else{
$birthdate = trim($_POST['birthdate']);
}
if (empty($_POST['gamespyid'])){
$errors[] = 'Your forgot to enter your gamespy id.';
}else{
$gamespyid = trim($_POST['gamespyid']);
}
if (empty($errors)) {
require ('mysqli_connect.php');
$q="INSERT INTO Users (firstname, lastname, username, password1, birthdate, gamespyid, base) VALUES ('$firstname', '$lastname', '$username', SHA1('$password1'), '$birthdate', '$gamespyid', '$base')";
$r = #mysql_query($dbc, $q);
if ($r){
echo'<p>You are now registered</p>';
}else{
echo'<p>You have not been registered</p>';
}
} else {
echo 'Error<br> <p>The following errors have occured:<br/>';
foreach ($error as $msg) {
echo " - $msg<br/>\n";
}
echo '</p><p>Please try again.</p><p><br/></p>';
} //if no errors
} //submit
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<form action="../pages/register.inc.php" method='POST'>
<table summary="REgform">
<tr>
<td>First Name:</td>
<td><input type='text' name='firstname' value='<?php echo $firstname; ?>'></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type='text' name='lastname'value='<?php echo $lastname; ?>'></td>
</tr>
<tr>
<td>Username:</td>
<td><input type='text' name='username'value='<?php echo $username; ?>'></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password1'></td>
</tr>
<tr>
<td>Repeat Password:</td>
<td><input type='password' name='password2'></td>
</tr>
<tr>
<td>Birthdate:</td>
<td><input type='text ' name='birthdate'value='<?php echo $birthdate; ?>'></td>
</tr>
<tr>
<td>Gamespy Id:</td>
<td><input type='text' name='gamespyid'value='<?php echo $gamespyid; ?>'></td>
</tr>
<tr>
<td>Base:</td>
<td><select name="base" size="1">
<option>
Select One
</option>
<?php require('http://www.virtual-aviation.org/gatewayaviation/admin/mysqli_connect.php');
$q = "SELECT id, CONCAT_WS(' ', airport_name, airport_code) FROM airports ORDER BY airport_code ASC";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0) {
while ($row = mysql_fetch_array ($r, MYSQL_NUM)) {
echo "<option value=\"$row[0]\"";
if (isset($_POST['existing']) && ($_POST['existing'] == $row[0]) ) echo 'selected="selected"'; echo ">$row[1]</option>\n";
}
} else {
echo '<option>Please a new airport first.</optioon>';
}
mysqli_close($dbc);
?>
</select></td>
</tr>
</table>
<p><input type='submit' name='submit' value='Register'></p>
</form>
</body>
</html>
Errors found in the dropdown box area
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home5/virtua15/public_html/gatewayaviation/pages/register.inc.php on line 178
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /home5/virtua15/public_html/gatewayaviation/pages/register.inc.php on line 180
Please a new airport first.
You can't require from 'http'. You need to change
require('http://www.virtual-aviation.org/gatewayaviation/admin/mysqli_connect.php');
to some local path like
require('mysqli_connect.php');
IMHO First check your mysql query by echoing it and then run the query through editor.
Second, although you have set display_errors but still you might not able to view the errors.

Why does my form send the data twice after refresh?

I have a form in my website, but I can't fix one problem. When I write some text in the form box, it sends the data to the database. When I hit refresh, the page sends the same data again, to the database. What is the problem with my code?
<?php
if(isset($_POST['submit']))
{
$err = array();
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$uname = $_SESSION['uname'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else
{
if(empty($sub) && empty($msg))
$err[] = "All field required";
else
{
if(empty($sub))
$err[] = "Subject Requried";
if(empty($msg))
$err[] = "Message Requried";
}
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red><b>$er</b></font>";
}
}
else
{
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
echo "Discussion was submitted";
}
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
name="discussion">
<table width="240" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="width:230;"><b>Select your Discussion</b>
<select name="type">
<?php
$sqld = mysql_query("SELECT * FROM distype");
while($row = mysql_fetch_assoc($sqld))
{
$d_id = $row['d_id'];
$diss = $row['type'];
echo "<option value='$diss'>$diss</option>";
}
?>
</select></td>
</tr>
<tr>
<td><b>Subject</b></td>
</tr>
<tr>
<td><input type="text" name="sub" value="" size="33" class=""/></td>
</tr>
<tr>
<td><b>Message</b></td>
</tr>
<tr>
<td><textarea cols="30" rows="3" name="msg" class=""></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit Form"><br>
<td></td>
</tr>
</table>
On successful form submit you need to reload the url or redirect him somewhere to prevent user from inserting data to the database.
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
header("Location: page.php?mode=success");
//or
header("Location: ".$_SERVER['REQUEST_URI']); //which will just reload the page
}
The problem is, that your code will execute the same way when sent the same data. You need to protect against double inserts by one of many contructs:
Unique key on the table
Store hash of last post in session, refuse post if it has the same hash as stored
redirect user to different page on succes, so that a refresh will not cause the same POST

Categories