getting white screen after executing php code - php

Hi I am working on a simple php registration. But everytime I am submitting the registration page, i am getting a blank screen, no error, no display.
The code in my php file is :
<?php
if($_SERVER['REQUEST_METHOD']=="POST"){
$IP = //my hostname
$dbuser = "my user id";
$conn = new mysqli_connect($IP, $dbuser, "","my databse name");
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$address = $_POST['address'];
$query = "SELECT email FROM user where email='".$email."'";
$result = mysqli_query($conn,$query);
$numResults = mysqli_num_rows($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // Validate email address
{
$message = "Invalid email address please type a valid email!!";
}
elseif($numResults>=1)
{
$message = $email." Email already exist!!";
}
else
{
mysqli_query("(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
echo $message = "Signup Sucessfully!!";
}
mysqli_close($conn);
}
print_r(error_get_last());
?>
there is no issue in establishing connection as i am using this connection method in other pages and they are working fine. Also i should specify that currently i am working on cloud 9 and my mysql database is on cloud9 itself.
please help me in undersstanding the trouble.

You say your line 42 has the insert query. I suppose you mean this query:
mysqli_query("(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");
As your error says "2 parameters expected", you are missing here your connection parameter. You should have this:
mysqli_query($conn, "(insert into user(name,phone_number, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".$pass1."','".$pass2."','".$address."')");

Put this in on the first line of your script
ini_set('display_errors', '1');
This will then display the errors on the page and you will be able to see what is going wrong.
Also rather than the IP address try "localhost"
$conn = new mysqli_connect("localhost", $dbuser, "","my databse name");
If the database is on the same machine this may solve your problem.

Also your code is incredibly unsafe and will suffer from SQL injection. Please consider the following lines:
$email = $_POST['email'];
$query = "SELECT email FROM user where email='".$email."'";
Basically you put whatever the user is passing into your SQL statement. What if he enters "' OR 1; DROP TABLE user". You would lose all your data.
Please read about SQL injection and use PDO:
http://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/fr/book.pdo.php

Related

PHP MySQL. Add table contents does not work

If I want to add content to the table using "INSERT INTO", I don't get an error message and the table is not filled. I'm new with PHP. explanations would be nice. The database runs on XAMPP.
I don't know what to try. I've already used another table, but it doesn't work. The user should have full access to the table. The names also match.
<?php
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if($passwort == $passwort2) {
echo "Password is correct.";
$db = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
} else if(!($passwort == $passwot2)) {
echo "Password is not correct";
} ?>
The variable $db actually contains information about the connection. You cannot insert a query into your database the way you are trying to
You can use $db (in your case) in order to check whether the connection has been correctly established or not and then if everything works correctly you can user mysqli_query() to inject the query into your database.
You can do it like so:
<?php
if(isset($_POST['submit'])){ //You have to check if your submit button is pressed
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if(!$db){
die('Connection could not be established! Check provided information');
}
if($passwort == $passwort2) {
echo "Password is correct.Inserting query now";
$query = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
$result = mysqli_query($db, $query); //keep $result for debugging purposes.
} else {
die("Password is not correct");
} //no need for else if as there are only 2 conditions.
if(!$result){ //check if query was successful.
die('Query Error');
}
echo "Query Updated successfully";
}
?>
This code is really simplistic and for testing purposes only.
I just wanted to show you the way you can send queries to your database. You better use other encryption techniques i.e. crypt() and of course functions like mysqli_real_escape_string() when retrieving data from users, in order to avoid potential injection attacks.
Check this post for more info about preventing injections.
Hope that helps.

error connecting to mysql database through crazy domains

newbie here! I have made a simple form on my site
warning message
I can't seem to figure out what i've done wrong.
This is the php code:
<?php
$servername = "localhost";
$dbusername = "charityh_root";
$dbpassword = "";
$dbname = "charitydb";
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$state = $_POST['state'];
$email = $_POST['email'];
//$password = $_POST['password'];
//$sha1password = sha1($password);
//Create connection
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
//Check connection
If ($conn -> connect_error) {
die("Connection failed:" . $conn -> connect_error);
}
Line 17 is $conn = newmysqli($...
any idea guys?
Mysql database wizard
Connecting to database now although when i enter in the details (first name, last name, state and email) i get the message first name can not be left blank...
if (empty($fname)) {
Echo "First name can not be blank. Please press back and correct the
issue";
die();
}
if (empty($lname)) {
Echo "Last name can not be blank. Please press back and correct the issue!";
die();
}
if (empty($state)) {
Echo "State can not be blank. Please press back and correct the issue!";
die();
}
if (empty($email)) {
Echo "Email can not be blank. Please press back and correct the issue!";
die();
}
$sql = "INSERT INTO charityh_database (First_Name, Last_Name, State, Email)
VALUES ('$fname', '$lname', '$state', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Thank You";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close ();
?>
$dbusername = "charityh_root";
$dbpassword = "";
Seems like you are using the same username and password as you were using in your local server. You need to replace them with the username and password crazy domain's.
Since as far as I know Crazy Domain deosn't allows a blank password.
EDIT
Besides that I can see the database name you have mentioned in the codes is "charitydb"; which should be something like charityh_database.(By looking at your recent edit this is a wild guess)
The error indicates your username and password do not have access to the database.
Have you checked the database will allow you to connect, using the username and password?

Inputting form data into Mysql database using php

I'm very new to MySQL. I'm trying to create a php script which reads data from a html form and stores it into the database. I'm also uploading an image whose path is saved in database and the image itself is stored in c:wamp/www/uploads. Now when I'm running the script on my wamp server after submission of my form I'm getting a blank page. When i check my uploads folder, it's still empty. So image isn't put into the folder. Can anyone debug it?
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'userdatadelta');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$table= "CREATE TABLE `users`
( `rollno` int(15) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`imageid` varchar(50) NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `username` (`email`))";
mysqli_query($db,$table);
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$roll_number = $_POST["rollno"];
$department = $_POST["department"];
$year = $_POST["year"];
$email = $_POST["email"];
$password = $_POST["password"];
$filename=$_FILES['userpic']['name'];
$filetype=$_FILES['userpic']['type'];
$name = mysqli_real_escape_string($db, $name);
$roll_number = mysqli_real_escape_string($db, $roll_number);
$department = mysqli_real_escape_string($db, $department);
$year = mysqli_real_escape_string($db, $year);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$newfilename= $roll_number;
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'upload/'.$newfilename);
$filepath="upload/".$newfilename;
}
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
echo "An account has been created with this email ID already. We regret the inconvenience";
}
else
{
$query = mysqli_query($db, "INSERT INTO users (name, rollno, department, year, email, password, imagepath)VALUES ( '$name','$roll_number', $department, $year,'$email', '$password', '$filepath')");
if($query)
{
echo "Thank You! You have completed registration and are now registered.";
}
}
}
?>
Edited code which works for the most part but for the insertion of data :(. The 2 comments "An account has been created with this email ID already. We regret the inconvenience" and "Thank You! You have completed registration and are now registered." don't seem to work.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$DB_SERVER="localhost";
$DB_USERNAME="root";
$DB_PASSWORD="";
$DB_DATABASE="userdatadelta";
$db = mysqli_connect( "$DB_SERVER" ,"$DB_USERNAME","$DB_PASSWORD","$DB_DATABASE")or die("Cannot connect");
echo "Got connected?";
if(isset($_POST["submit"]))
{
echo "Got inside isset!";
$name = $_POST["name"];
$roll_number = $_POST["rollno"];
$department = $_POST["department"];
$year = $_POST["year"];
$email = $_POST["email"];
$password = $_POST["password"];
$filename=$_FILES['userpic']['name'];
$filetype=$_FILES['userpic']['type'];
$name = mysqli_real_escape_string($db, $name);
$roll_number = mysqli_real_escape_string($db, $roll_number);
$department = mysqli_real_escape_string($db, $department);
$year = mysqli_real_escape_string($db, $year);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$newfilename= $roll_number;
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
echo "Got inside file type checking!";
move_uploaded_file($_FILES['userpic']['tmp_name'],'upload/'.$newfilename);
$filepath="upload/".$newfilename;
}
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
echo "An account has been created with this email ID already. We regret the inconvenience";
}
else
{
$query = mysqli_query($db, "INSERT INTO users (name, rollno, department, year, email, password, imagepath)VALUES ( '$name','$roll_number', $department, $year,'$email', '$password', '$filepath')");
echo "Got inside else!";
if($query)
{
echo "Thank You! You have completed registration and are now registered.";
}
}
}
echo "Comment!";
?>
With such a long code snippet its hard to determine possible errors, as the blank page can be caused from many reasons.
Some of the typical problems that could be related to your code:
a PHP syntax error like an extra or missing brace ( { or } ), for example. The piece you posted seems to be ok, but you dont't tell which PHP version are you using.
a denied write permission to upload path. Either because permissions are wrong, or the path is incorrect. You don't specify your operating system, but it's assumed to be Windows. Some systems use case insensitive paths, other case sensitive, check that for the version and configuration of your current system.
for blank page issue, even when no errors would be raised, there is a sequence of execution in which neither one of the two echo calls are being triggered.
Tipically, PHP will not output any errors to the users as in a production environment it may represent a security risk.
In your development environment you can enable error output to quickly address what is going wrong.
Add the following lines just right after the first opening <?php clause:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Now all the errors for what PHP is complaining should be outputted to the browser.
Be aware, this is not considered a good practice specially in production environments. Errors should be looked up on log files. Use it for helping yourself debugging and solving your current problem in develpment time. If you are working on a large project consider getting the help of a PHP framework to enhance your coding experience.

Registration script.php does not work

I have a registration script that doesn't work. It used to work but then suddenly it stopped working. I dont know what I've done or what happend. I have tried for like an hour now to find out where the problem is, but I can't seem to find it.
What happens? When I click register I don't get any errors but it doesn't upload to the database:
When I type: $res = mysql_query($query) or die ("ERROR"); it displays ERROR so I think it's related to that code:
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);
$country = mysql_real_escape_string($_POST['country']);
$rights = '0';
$IP = $_SERVER['REMOTE_ADDR'];
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$query = mysql_query("SELECT username FROM users WHERE username = '".$username."'");
if (mysql_num_rows($query) > 0)
{
echo 'Username or email already in use.';
}
else{
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country',$rights,$IP,NOW())" ;
$res = mysql_query($query);
header("location:load.php");
}
}
I think you are getting the error because you are missing some quotes in your query for two columns wich really looks like not integers
'$email','$country',$rights,$IP,NOW())" //$rights and $ip doesn't have quotes
so your query would look like
"insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country','$rights','$IP',NOW())"
Use mysql_error() in order to see what the error message is. If you haven't changed anything in the script then it's either your database structure has changed or your rights have.
Update:
You don't have quotes around your IP value, which is surprising because you said that query worked until now. Anyway you should also consider saving IPs the RIGHT way. Good luck!

mySQL not saving data?

i have a PHP contact form that submits data, and an email...:
<?php
$dbh=mysql_connect ("localhost", "username", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("guest");
if (isset($_POST['submit'])) {
if (!$_POST['name'] | !$_POST['email'])
{
echo"<div class='error'>Error<br />Please provide your Name and Email Address so we may properly contact you.</div>";
}
else
{
$age = $_POST['age'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$query = "INSERT INTO contact_us (age,name,gender,email,phone,comments)
VALUES ('$age','$name','$gender','$email','$phone','$comments')";
mysql_query($query);
mysql_close();
$yoursite = "Mysite ";
$youremail = $email;
$subject = "Website Guest Contact Us Form";
$message = "$name would like you to contact them
Contact PH: $phone
Email: $email
Age: $age
Gender: $gender
Comments: $comments";
$email2 = "my#email.com";
mail($email2, $subject, $message, "From: $email");
echo"<div class='thankyou'>Thank you for contacting us,<br /> we will respond as soon as we can.</div>";
}
}
?>
The email is coming through fine, but the data is not storing the dbase... am i missing something?
Its the same script as i use on another contact us page, only difference is instead of parsing the data on teh same page, i now send this data to a "thankyou.php" page... i tried changing $_POST to $_GET but that killed the page... what am i doing wrong?
First of all, you must escape your data before injecting them in your SQL query.
This can be done using the mysql_real_escape_string function, like this :
$name = mysql_real_escape_string($_POST['name']);
// ... same for other fields that contain strings
$comments = mysql_real_escape_string($_POST['comments']);
This will ensure that quotes in your data are escaped, and don't mess with the ones that are arround the fields' data in the SQL query, first.
And, second, this will help you prevent SQL Injections.
Also, in case of an error during the execution of a query, mysql_query will return false -- which means you should test the value returned by that function -- to possibly log the cause of the error :
$result = mysql_query($query);
if ($result === false) {
// An error has occured...
echo mysql_error();
}
Note : here, I just displayed the error message -- but you should instead log the error somewhere (to a file, for instance), before putting your application to production : your users don't need (nor want) to see any technical error message !
Check the result from mysql_query(...) to see if it failed or not. If it didn't fail, MySQL should definitely have stored the information for you.

Categories