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.
Related
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.
Here's the PHP code:
<?php
$servername = "***";
$username = "*****";
$password = "*****";
$database = "*****";
try {
$conn = new PDO('mysql:host='.$servername.';dbname='.$database, $username, $password);
console.log('yes!');
}
catch(PDOException $e) {
print "Error!:" . $e->getMessage(). "<br/>";
die();
}
if (isset($_POST['submit']))
{
//$name = $_POST['name'];
//$day = $_POST['day'];
//$acctName = $_POST['acctName'];
//$acctType = $_POST['acctType'];
//$location = $_POST['location'];
//$prospect = $_POST['prospect'];
//$notes = $_POST['notes'];
$name = 'sally sue';
$day = 'monday';
$acctName = 'Account Uno';
$acctType = 'Cold Call';
$location = 'Location';
$prospect = 'Prospect';
$notes = 'These are notes! Notey notey notes';
$order = "INSERT INTO `schedule`(`id`, `name`, `day`, `acctName`, `acctType`, `location`, `prospect`, `notes`) VALUES ('$name', '$day', '$acctName', '$acctType', '$location', '$prospect', '$notes')";
$stmt = $conn->prepare($order);
$stmt->execute();
}
?>
Here's the deal. I have an HTML form that I use jQuery to grab the variables, and AJAX to post the form to this PHP file. I feel confident that everything is fine up to the point where it gets to the PHP file.
I commented out the POST variables and hard-coded my own to make it a little simpler. I'm not getting a 500 Internal Server Error. I've ran my code through a PHP syntax validator (and fixed a billion errors haha). Obviously I'm still doing something wrong, but I cannot find it for the life of me. I'm hoping that someone here has some insight?
EDIT: Also, the username, password, database, and table name are ALL correct. I've double checked them several times. The only thing I'm not sure of is the server name, which is 'localhost' since the DB is on the same server as this web page.
EDIT 2: I've changed the MySql insert statement back to the original, which had the back ticks. I copied it straight from phpMyAdmin console on the server which it resides. It was that way originally, but I changed it due to desperation. It still is not updating my database. Any further ideas?
Thanks in advance!
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
I have a simple user registration form and external connection script with some strange results.
The page register.php shows the form fine, however seems to display my entire connection string before the form?
It then throws up errors in relation to my connection variable '$dbcon' (I have commented the line at which this happens) Here is my register.php code:
<?php
session_start();
require "connect.php";
if (isset($_SESSION['username'])){
header("location: members.php");
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if ($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill all fields";
}
else
{
if ($pass != $rpass)
{
echo "Passwords do not match";
}
else
{
//This is where the errors are found
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user' ") or die ("Cannot query table");
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "This username is already taken";
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Cant insert data");
echo "Successfully added user!";
}
}
}
}
?>
And here is my connection file 'connect.php' (the $dbcon string is the one that prints out??)
$server = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'bodgett';
$dbcon = mysqli_connect($server, $user, $pass, $dbname)or die("Can not connect to Server.");
Specifically, the error is 'Notice: Undefined variable: dbcon in C:\webserver...\register2.php'
Can anyone suggest why is doesn't recognize this variable?
Probably a wrong filename (maybe file isn't called connect.php) OR wrong file extension? (html instead of .php)
I just copied all your code, and it works for me. Aswell I don't see php start and closing Tags.
I agree with #Xatenev. Also, you may want to consider using PDO for your database interactions, it's the most secure way. I found this very helpful: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Sorry if this seems irrelevant, just trying to help.
The connection file 'connect.php' is not enclosed within tags, hence not usable and explains why the text was simply printing out at the top of the page.
Check if mysqli extension is enabled
the code that generates $dbcon is inside a class or inside some function?
If yes, maybe you need to return or call it properly.
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!