I am having trouble creating this login system. When someone logs in I want it to create a table, if not already. Then bring them to the form page, then insert the data. I have everything working until the insert on the last page.
After Steam API Login
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
$query = "SELECT * FROM `".$steamid."`";
$response = #mysqli_query($dbc, $query);
if($response){
header("Location: http://theskindealer.com/index.php");
} else {
$create = "CREATE TABLE `".$steamid."` (
steam64 VARCHAR(30),
fullname VARCHAR(60),
tradeurl VARCHAR(60),
email VARCHAR(50),
age INT(3),
tos INT(1),
access INT(1),
freeze INT(1),
balance DECIMAL(9,2),
newsletter INT(1),
emailVerified INT(1)
)";
if ($dbc->query($create) === TRUE) {
header("Location: http://theskindealer.com/scripts/createAccount.php");
} else {
header("Location: http://theskindealer.com/pages/errorlogin.php");
}
}
$stmt->close();
$dbc->close();
?>
Then it REDIRECTS to the form page:
<!DOCTYPE HTML>
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
?>
<html>
<head>
<title>TheSkinDealer | Setup</title>
<link rel="stylesheet" type="text/css" href="../css/accept.css"></head><body>
<div id="content">
<div id="acceptbox">
<img src="../images/logo.png">
<form action="setup.php" method="post">
<div id="name1">Full Name:</br> <input type="text" name="fullname"> </br></div>
<div id="name1">TradeURL: <a target="_blank" href="http://steamcommunity.com/id/me/tradeoffers/privacy#trade_offer_access_url">(?)</a></div> <input type="text" name="tradeurl"> </br>
<div id="name1">EMAIL:</div> <input type="text" name="email"> </br>
<div id="checkboxes">
Terms Of Serice: <input type="checkbox" name="tos" value="1"> </br>
18 Or Older: <input type="checkbox" name="age" value="1"></br>
Newsletter: <input type="checkbox" name="newsletter" value="1"></br>
</div>
<div id="returnhome">
<div id="accept"><input type="submit" value="Create Account"></a></div>
</div>
</form>
</div>
<center><div id="par">Purchases Or Sales Cannot Be Made Without Accepting TOS.</div></center>
</div>
</body>
</html>
Lastly the insert page:
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
$insert = "INSERT INTO `".$steamid."` (steam64, freeze, access,
tos, balance, age, email, tradeurl, fullname, newsletter, emailVerified)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $dbc->prepare($insert);
$stmt->bind_param('sssssssssss',
$steam64,
$freeze,
$access,
$tos,
$balance,
$age,
$email,
$tradeurl,
$fullname,
$newsletter,
$emailVerified
);
$steam64 = $steamid;
$freeze = 0;
$access = 0;
$tos = $_POST["tos"];
$balance = 0.00;
$age = $_POST["age"];
$email = $_POST["email"];
$tradeurl = $_POST["tradeurl"];
$fullname = $_POST["fullname"];
$newsletter = $_POST["newsletter"];
$emailVerified = 0;
$stmt->execute();
header("Location: http://theskindealer.com/");
$stmt->close();
$dbc->close();
?>
Do you get any errors when executing this script?
You could for instance add error_reporting(E_ALL); to the top of your script to get a better look at errors.
Looking at the script it seems like you are binding variables before they exist.
You should put the variable assigments before the bind_param exetution:
$steam64 = $steamid;
$freeze = 0;
$access = 0;
$tos = $_POST["tos"];
$balance = 0.00;
$age = $_POST["age"];
$email = $_POST["email"];
$tradeurl = $_POST["tradeurl"];
$fullname = $_POST["fullname"];
$newsletter = $_POST["newsletter"];
$emailVerified = 0;
$stmt->bind_param('sssssssssss',
$steam64,
$freeze,
$access,
$tos,
$balance,
$age,
$email,
$tradeurl,
$fullname,
$newsletter,
$emailVerified
);
$stmt->execute();
Also keep in mind that numeric values like 0 must be bind with 'i' instead of 's'
See http://php.net/manual/de/mysqli-stmt.bind-param.php for more info.
For instance.
$stmt->bind_param('iiisdissssi',
Related
I am new to PHP and web development, and trying to create an HTML form that will submit data into MYSQL.
Upon checking phpmyadmin after submission of the form, it shows that there has been a row submitted,
however the row is completely blank. I had a problem before this one, that instead of a blank row, it would be "1" submitting instead of the data inserted into the HTML form. Now, no data submits into the database.
Here is the PHP:
<?php
Include("connection.php");
// HTML Identification
$lname = isset($_POST['lastname']);
$fname = isset($_POST['firstname']);
$email = isset($_POST['email']);
$phone = isset($_POST['phonenum']);
$addr = isset($_POST['address']);
$city = isset($_POST['city']);
$state = isset($_POST['state']);
$zip = isset($_POST['zipcode']);
//Database Insertion
$sql= "INSERT INTO CustomerInfo (LastName, FirstName, Email, PhoneNum, Address, City, State, ZipCode)
VALUES ('$lname', '$fname', '$email', '$phone', '$addr', '$city', '$state', '$zip')";
// Insertion
$ds= mysqli_query($conn, $sql);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
?>
The HTML Form:
!DOCTYPE html>
<html>
<head>
<title> GS Entry Form </title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css#2/out/water.css" </link>
<style>
h1 {text-align: center;}
h2 {text-align: center;}
</style>
</head>
<body>
<h1>Customer Entry Form</h1>
<h2>Please Input Contact Information</h2>
<form action="database.php" method="POST">
First Name:<br />
<input type="text" name="firstname" />
<br /><br />
Last Name:<br />
<input type="text" name="lastname" />
<br /><br />
Email:<br />
<input type="text" name="email" />
<br /><br />
Phone Number:<br />
<input type="text" name="phonenum"/>
<br /><br />
Address:<br />
<input type="text" name="address"/>
<br /><br />
City:<br />
<input type="text" name="city"/>
<br /><br />
State:<br />
<input type="text" name="state"/>
<br /><br />
Zip Code:<br />
<input type="text" name="zipcode"/>
<br /><br />
<button type="button" name= "submit" value= "submit" />
</form>
</body>
</html>
Here, also, is the connection.php referenced:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create Connection
$conn= mysqli_connect("$servername:3306","$username","$password","$dbname");
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " .$conn->connect_error);
}
else echo "Connection successful! "
?>
I don't think it has anything to do with the connection, but I figured I would post it to cover all the bases. The attached imgur picture is what my database has been looking like after submissions have been made.
I truly am not sure what to do now, any help would be greatly appreciated.
Thank you! -G
EDIT:
This is what my PHP code looks like after the changes suggested from #EinLinuus:
<?php
Include("connection.php");
// HTML Identification POST
if(isset($_POST['firstname'])) {
$fname = $_POST['firstname'];
}else{
die("Firstname is missing");
}
if(isset($_POST['lastname'])) {
$lname = $_POST['lastname'];
}else{
die("Lastname is missing");
}
if(isset($_POST['email'])) {
$email = $_POST['email'];
}else{
die("Email is missing");
}
if(isset($_POST['phone'])) {
$phone = $_POST['phone'];
}else{
die("Phone Number is missing");
}
if(isset($_POST['addr'])) {
$addr = $_POST['addr'];
}else{
die("Address is missing");
}
if(isset($_POST['city'])) {
$city = $_POST['city'];
}else{
die("City is missing");
}
if(isset($_POST['state'])) {
$state = $_POST['state'];
}else{
die("State is missing");
}
if(isset($_POST['zip'])) {
$zip = $_POST['zip'];
}else{
die("Zip Code is missing");
}
//Database Insertion
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt= $conn->prepare("INSERT INTO CustomerInfo(FirstName, LastName, Email, PhoneNum, Address, City, State, ZipCode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssssss', $fname, $lname, $email, $phone, $addr, $city, $state, $zip);
$stmt->execute();
// Insertion
$sql= mysqli_query($conn, $stmt);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
$stmt->close();
$conn->close();
?>
My HTML remains the same, besides adding ID attributes to each variable to no effect. I appreciate the help!
The isset function returns if the variable is declared or not -> the return type is a boolean.
$test = [
"hello" => "world"
];
var_dump(isset($test["hello"])); // bool(true)
var_dump(isset($test["something"])); // bool(false)
You can use isset to check if the field exists in the $_POST variable, but don't save the result of the isset function to the database. If you do so, the boolean will be converted to a number (true => 1, false => 0) and this number gets stored in the database.
Example:
if(isset($_POST['lastname'])) {
die("lastnameis missing");
}
$lname = $_POST['lastname'];
Security
This code is vulnerable to SQL Injections. You should never trust user input. I'd recommend to use prepared statements here:
$stmt = $mysqli->prepare("INSERT INTO CustomerInfo (LastName, FirstName, ...) VALUES (?, ?, ...)");
$stmt->execute([$lname, $fname]);
In the SQL statement, replace the actual values with ?. Now you can execute the statement and pass the values to the execute function. In the example above, $lname will replace the first ?, $fname the second, ...
I need to update a PDF file that already has been uploaded for a certain user (using html form). I have added a code to update the PDF document (to choose another/new document) but it is not working. It is just updating the name of the file to the database without uploading the file to the folder and the path to the database like I have in my insert.php.
This is my insert.php code:
<?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "employees";
// Create connection
$conn = mysqli_connect($server, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$dob = mysqli_real_escape_string($conn, $_POST['dob']);
$embg = mysqli_real_escape_string($conn, $_POST['embg']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$workplace = mysqli_real_escape_string($conn, $_POST['workplace']);
$workposition = mysqli_real_escape_string($conn, $_POST['workposition']);
$jobstartdate = mysqli_real_escape_string($conn, $_POST['jobstartdate']);
$contractfrom = mysqli_real_escape_string($conn, $_POST['contractfrom']);
$contractto = mysqli_real_escape_string($conn, $_POST['contractto']);
$healthbookfrom = mysqli_real_escape_string($conn, $_POST['healthbookfrom']);
$healthbookto = mysqli_real_escape_string($conn, $_POST['healthbookto']);
$bankaccount = mysqli_real_escape_string($conn, $_POST['bankaccount']);
$bank = mysqli_real_escape_string($conn, $_POST['bank']);
$workcode = mysqli_real_escape_string($conn, $_POST['workcode']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$bloodtype = mysqli_real_escape_string($conn, $_POST['bloodtype']);
$notes = mysqli_real_escape_string($conn, $_POST['notes']);
$contract_file = basename($_FILES['contractupload']['name']);
$contract_path = "files/contracts/$contract_file";
$contract_file = mysqli_real_escape_string($conn, $contract_file);
copy($_FILES['contractupload']['tmp_name'], $contract_path); // copy the file to the folder
$sql = "INSERT INTO addemployees (fname, lname, dob, embg, address, city, mobile, email, workplace, workposition, jobstartdate, contractfrom, contractto, healthbookfrom,
healthbookto, contractupload, bankaccount, bank, workcode, gender, bloodtype, notes)
VALUES ('$fname', '$lname', '$dob', '$embg', '$address', '$city', '$mobile', '$email', '$workplace', '$workposition', '$jobstartdate', '$contractfrom', '$contractto',
'$healthbookfrom', '$healthbookto', '$contract_file', '$bankaccount', '$bank', '$workcode', '$gender', '$bloodtype', '$notes')";
if (mysqli_query($conn, $sql)) {
header("location: employees.php");
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Use this to write text for the connection ---> echo "Connected successfully";
//Close the connection
mysqli_close($conn);
?>
This is my update.php code:
<?php
// Include config file
require_once "new_db_connect.php";
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$embg = $_POST['embg'];
$contractupload = $_POST['contractupload'];
$contract_file = $_FILES['contractupload']['name'];
$contract_path = "files/contracts/$contract_file";
copy($_FILES['contractupload']['tmp_name'], $contract_path);
$id = $_POST['id'];
// UPDATE the info
$sql = "UPDATE addemployees SET fname = '$fname', lname = '$lname', embg = '$embg', contractupload = '$contractupload' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
header("location: employees.php");
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
And this is my edit.php code:
<?php
// Include config file
require_once "new_db_connect.php";
if($_GET['id']) {
$id = $_GET['id'];
$sql = "SELECT * FROM addemployees WHERE id = {$id}";
$result = $connect->query($sql);
$data = $result->fetch_assoc();
$connect->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Update User Info</h2>
</div>
<form action="update.php" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" id="fname" name="fname" class="form-control" value="<?php echo $data['fname'] ?>">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" id="lname" name="lname" class="form-control" value="<?php echo $data['lname'] ?>">
</div>
<div class="form-group">
<label>ID Number</label>
<input type="text" id="embg" name="embg" class="form-control" value="<?php echo $data['embg'] ?>">
</div>
<div class="form-group">
<label>Contract PDF</label>
<input type="file" name="contractupload" id="contractupload" class="form-control" style="border: 1px solid #CED4DA!important;" style="width: 50%!important;" value="<?php echo $data['contractupload'] ?>">
</div>
<input type="hidden" name="id" value="<?php echo $data['id'] ?>"/>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
}
?>
Update
I have updated my code so it can be more readable and more simple. I am looking for help with updating the PDF file.
$_POST['contractupload'] won't work. The filename is only in $_FILES. You should process it the same way you do in insert.php.
I've also shown how to rewrite your code using a prepared statement instead of variable substitution.
And you should use move_uploaded_file() instead of copy(). See Difference between copy and move_uploaded_file.
<?php
// Include config file
require_once "new_db_connect.php";
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$embg = $_POST['embg'];
$contract_file = basename($_FILES['contractupload']['name']);
$contract_path = "files/contracts/$contract_file";
move_uploaded_file($_FILES['contractupload']['tmp_name'], $contract_path);
$id = $_POST['id'];
// UPDATE the info
$stmt = $connect->prepare("UPDATE addemployees SET fname = ?, lname = ?, embg = ?, contractupload = ? WHERE id = ?");
$stmt->bind_param("ssssi", $fname, $lname, $embg, $contract_file, $id);
if($stmt->execute()) {
header("location: employees.php");
} else {
echo "Erorr while updating record : ". $stmt->error;
}
$connect->close();
}
?>
I tried to write a registration form. On submition it suppose to:
Get the data from the inputs to the sql database - as a row in the table.
Add the users email address as a session variable.
Redirects them to a second page.
It all happens, but it adds two identical rows instead of one.
I'll appreciate any answer you can give me that will explain why my script adds the same row twice into the database.
PHP:
<?php
ob_start();
session_start();
if($_POST) {
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$error = "";
$link = mysqli_connect("xx", "xx", "xx", "xx");
if (mysqli_connect_error()) {
die("the connection was failed");
}
if ($email || $password || $name) {
$stmt = $link->prepare("INSERT INTO `Family` (email, password, name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $email, $password, $name);
$stmt->execute();
if($stmt->execute()) {
$_SESSION['email'] = $email;
header("Location: session.php");
$stmt->close();
} else {
echo "it failed";
}
}
}
HTML:
<html>
<head>
</head>
<body>
<h1>Registration Form</h1>
<form method="post">
<p>Email:</p>
<input type="email" name="email">
<p>Password:</p>
<input type="password" name="password">
<p>Name:</p>
<input type="text" name="name">
<br><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I'm trying to write a registration form, firstly I tried to do it OO, but this didn't respond, it seemed to just clear the form and refresh the page, but didn't insert any data:
EDIT: Current code:
<?php
session_start();
include 'registrationform.php';
include 'connection.php';
if (isset($_POST['regsubmit']))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user = $_POST['username'];
$pass = $_POST['password'];
$query = "INSERT INTO users (firstname, lastname, username, password) VALUES(?, ?, ?, ?)";
$statement = $connection->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssss', $firstname, $lastname, $username, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
//$_SESSION['username'] = $_POST['username'];
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
Registration Form
<!DOCTYPE html>
<?php
include 'header.php';
?>
<center>
<html>
<link rel="stylesheet" type="text/css" href="web.css" />
</font>
<head>
</head>
<body>
<div id="registrationform">
Please enter your registration details<br /><br />
<form method="post" action="registrationsubmit.php">
First Name:
<input type="text" name="firstname" />
<br /><br>
Last Name:
<input type="text" name="lastname" />
<br /><br>
Username:
<input type="text" name="username" />
<br /><br>
Password:
<input type="text" name="password" />
<br /><br>
<input type="submit" name="regsubmit" value="Submit" />
</form>
</div>
</body>
</html>
</center>
OO Attempt
<?php
session_start();
include 'registrationform.php';
include 'connection.php';
if (isset($_POST['regsubmit']))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user = $_POST['username'];
$pass = $_POST['password'];
$stmt = $connection->prepare("INSERT INTO users VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $firstname, $lastname, $user, $pass);
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
$stmt->close();
}
?>
As this wasn't working I tried just doing it without OO, for a starting point. But now I'm given the error "Access denied for user ''#'10.246.64.24' (using password: NO)", yet my connection connects fine and I've also written a login that works perfectly so can't figure it out. Here is the current code that I have:
registrationsubmit.php
<?php
include "connection.php";
include "header.php";
if(isset($_POST['regsubmit']))
{
mysql_select_db("c3438525_co_uk",$connection);
$firstname = $_POST['$firstname'];
$lastname = $_POST['$lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO users (FirstName, LastName, Username, Password) VALUES ('$firstname', '$lastname', '$username', '$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data) { echo "Successfully Registered"; }
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
?>
Connection.php
<?php
ob_start();
$connection = mysqli_connect("***", "***", "BFUWGpn3", "***");
?>
You're using a mysqli_ connection and your query is mysql_
For the registrationsubmit.php
Use something on the lines:
$query = "INSERT INTO users (firstname, lastname, username, password) VALUES(?, ?, ?, ?)";
$statement = $connection->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssss', $firstname, $lastname, $username, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
//$_SESSION['username'] = $_POST['username'];
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
Refer to : http://php.net/manual/en/mysqli.insert-id.php
I have a table named 'Directors' in the database 'db2'.
I have an HTML form. I would like when I insert the values and hit submit button, to insert the content into the table in a new row (to INSERT INTO), after it makes some validations (you'll notice them in the script). I've tried to do it by myself, but it is always echoing me 'Fail';
This is my HTML form:
<form action="process.php" method="post" accept-charset="utf-8">
<input type="hidden" name="pages_edit_nonce" />
<div class="section-item page-title-section">
<label for="title">Full Name:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="name" value="" /></div> </div>
<div class="section-item">
<label for="label">Phone:</label><span class="help">*Optionally</span><div class="input-wrap"><input type="text" name="phone" value="" /></div> </div>
<div class="section-item">
<label for="redirect">Е-mail:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="email" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">School:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="school" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">City:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="city" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">Password:</label><span class="help">*</span><div class="input-wrap"><input type="password" name="password" value="" placeholder="" /></div> </div>
<div class="admin-bar">
<div class="admin-bar-inner">
<input type="submit" value="Submit" class="btn" />
</div>
</div>
</form>
This is my process.php file:
$server = "localhost";
$user = "****";
$pass = "****";
$conn = mysql_connect($server, $user, $pass);
$db = mysql_select_db("****", $conn);
session_start();
if(!$db) {
$_SESSION['ERRMSG'] = "<strong>Error:</strong> The access to the database is denied!";
header("Location: ../../admin/error/");
exit();
}
session_start();
function UniqueID() {
$UID = rand(); //Create unique ID
$check = mysql_query("SELECT * FROM `Directors` WHERE `UID` = '$UID'");
if(mysql_num_rows($check) > 0) { //Check if it exists
UniqueID(); //Redo the function
} else {
return $UID; //return the uniqueid
}
}
$UID = UniqueID(); //Unique ID
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$school = $_POST['school'];
$city = $_POST['city'];
//Create INSERT query
$qry = "INSERT INTO `oclass`.`Directors`(`UID`,`Name`, `Phone`, `Email`, `SchoolGymnasium`, `City`, `Password`) VALUES('$UID','$name','$phone','$email','$school','$city','" . md5($password) . "')";
$result = mysql_query($qry);
//Check whether the query was successful or not
if($result) {
$_SESSION['SUCCMSGADDDIR'] = 'Sucessful.';
header("location: URL");
exit();
} else {
$_SESSION['ERRMSGADDDIR'] = 'Fail';
header("location: URL");
}
After changing the error session with mysql_error() it gave me the following error:
Fatal error: Can't use function return value in write context in ... on line 10;
Line 10 is:
mysql_error() = "<strong>Error:</strong> The access to the database is denied!";
I've removed the column named ID (which was Primary Key) and set UID column as Primary Key, and now is working. Thank you guys.
Firstly you must have never heard of SQL injection http://en.wikipedia.org/wiki/SQL_injection. Your current code is opening you up for attacks. You can't directly insert user input into the database like you're doing. Also mysql_* functions are deprecated. To help your code be safer and more update try something like this:
session_start();
$host = "localhost";
$user = "****";
$pass = "****";
$db = "****";
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO `oclass`.`Directors`(`UID`,`Name`, `Phone`, `Email`, `SchoolGymnasium`, `City`, `Password`) VALUES (:uid, :name, :phone, :email, :school, :city, :password)");
$stmt->bindParam(':uid', uniqid());
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':school', $_POST['school']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':password', md5($_POST['password']));
$stmt->execute();