I have tried hard to debug the following insert.php file. There are no errors while running this and the associated webform file inwamp server, but it is not reading data to the database. Can someone comment on this?
?php
if (isset($_POST['submit'])) {
//Connect to the database
$host="localhost";
$user="root";
$password="";
$dbc=mysql_connect($host,$user,$password) or die("Connection Error");
$db_name="userregistration";
mysql_select_db("$db_name") or die ("Could not select database");
//Reading data from form and writing to the DB
$fname = $_POST['fname'];
$institution = $_POST['institute'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$pgm = $_POST['pgm'];
$address = $_POST['address'];
//Examining for input errors
$error = FALSE;
if (isset($address)) {
$address = trim($address);
$address = strip_tags($address);
}
if (isset($fname) &&
isset($institute) &&
isset($email) &&
isset($phone) &&
isset($pgm) &&
isset($address) &&
$error == FALSE) {
$process = TRUE;
} else {
$process = FALSE;
}
//Writing the multiple answers for user selected programs
while ((list($key,$val) = each($pgm))) {
$pgm .= "[" . $val . "]";
}
//Creating the table
$query = "create table userdata
( sid int unsigned not null auto_increment primary key,
fname char(50) not null,
institute char(50) not null,
email char(50) not null,
phone int unsigned,
pgm text not null,
address char(200) not null)";
$q = mysql_query($query);
//Inserting the data
$query = "insert into userdata values ('','$fname','$institute','$email','$phone','$pgm','$address')";
$q = mysql_query($query);
//Check whether data was properly inserted
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
echo "<p>MySQL Insertion Successful</p>";
}
}
?>
Can someone comment on this ?
try adding
or die(mysql_error());
after your mysql_query($query). That will surely show an error if it failed...
did you try to echo out $q ? it should tell exactly what's wrong when trying to add to database..
//Check whether data was properly inserted
if (!$q) {
die(mysql_error());
exit();
} else {
mysql_close();
echo "<p>MySQL Insertion Successful</p>";
}
My best guess is that the table already exists and so when the user submits the form your code is again trying to create the table 'userdata' which is already there and then dies.
You should remove the create statement out of your code because on every submission it's going to try and create a table that already exists. You should also look about escaping the submtted data before you pass on to an SQL statement as you're just asking for SQL injection attacks as the code stands now.
Related
I have a connect file which is included in the header of my files. The header contains a session start, and I have checked that the session ID is the same across pages. I am trying to echo the $_SESSION['userFirstName'] within some HTML to display the users name. I cannot figure out why it it is blank. There are no error messages from Chrome other than the "Notice: Undefined index: userFirstName
Here is my connect.php
<?php
/*Login handled here*/
$servername = "localhost";
$usernameDB = "root";
$passwordDB = "";
$nameDB = "teacheasy";
//set user and password to values from form
if ( isset($_POST['username']) && isset($_POST['password']) ) {
$user = $_POST['username'];
$pass = $_POST['password'];
} else {
echo "The values weren't sent";
}
//connect to the database
$_SESSION['connection'] = new mysqli($servername, $usernameDB, $passwordDB,$nameDB);
//Check if the connection was successful
if($_SESSION['connection']->connect_error){
die("Connection to the database failed: " . $_SESSION['connection']->connect_error);
} else{
//once the DB is connected, get information from the DB to check the records against the data entered
$sqlUser = "SELECT `teacher_username` FROM `teacher` WHERE `teacher_username`='$user'";
$sqlPass = "SELECT `password` FROM `teacher` WHERE `password`='$pass'";
$resultUser = mysqli_query($_SESSION['connection'], $sqlUser);
$resultPass = mysqli_query($_SESSION['connection'], $sqlPass);
$textUser = $resultUser->fetch_assoc();
$textPass = $resultPass->fetch_assoc();
//get first name and last name to populate the user
$sqlUserFirstName = "SELECT `first_name` FROM `teacher` WHERE `teacher_username`='$user'";
$sqlUserLastName = "SELECT `last_name` FROM `teacher` WHERE `teacher_username`='$user'";
$resultUserFirstName = mysqli_query($_SESSION['connection'], $sqlUserFirstName);
$resultUserLastName = mysqli_query($_SESSION['connection'], $sqlUserLastName);
$_SESSION['userFirstName'] = $_POST[$resultUserFirstName->fetch_assoc()];
$_SESSION['userLastName'] = $_POST[$resultUserLastName->fetch_assoc()];
//check if the user and password match records in the database
if($user == $textUser['teacher_username'] && $pass == $textPass['password']){
//open the calendar if they match
echo "<script> window.location.assign('../calendar.php'); </script>";
} else{
//set this up to load a log in failed page rather than a blank page with error message
echo "The data entered has no match.";
}
}
This is what you done
$user = $_POST['username']
// "SELECT `first_name` FROM `teacher` WHERE `teacher_username`='$user'" // SQL injection here
$_SESSION['userFirstName'] = $_POST[$resultUserFirstName->fetch_assoc()];
As #jeroen said in comments $_SESSION['userFirstName'] must be empty because there is no key in the $_POST that is equals $resultUserFirstName->fetch_assoc() which returns an array! . You should be getting an undefined index error.
$_POST is an array that holds the variables that have been posted with the http request to your server. It has nothing to do with the data returned from your database query unless $_POST['username'] === teacher.first_name and teacher.first_name === teacher.teacher_username
try
$_SESSION['userFirstName'] = $resultUserFirstName->fetch_assoc()['first_name'];
instead of
$_SESSION['userFirstName'] = $_POST[$resultUserFirstName->fetch_assoc()];
Also you are vulnerable to SQL injection attacks, and you should make it a happit to always use prepared statements. Check this answer on how to switch to prepared statements if you are used to concatenating.
I am programming an App and I have a problem now.
When I register a new student with the app a Query runs on my php Script and insert the new student in my database.
What I want to do now is, when I am registering him, I want my php Script to run a multiple query so that all the other tables should be filled with NULL and the query should get the ID from the new created student to link it with the other tables(foreign key).
I tried it with mysqli_multiple_query and LAST_INSERT_ID() but both didn't work.
How would it be possible to get that id in return from my insert?
Here is my php script.
<?PHP
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown) VALUES('$Name','$Surname','$Street','$Hometown')";
$sql .= "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES ("","","","","",LAST_INSERT_ID())";
if(mysqli_multi_query($con,$sql)){
echo 'successfully registered';
} else {
echo 'oops! Please try again!';
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
I hope someone can help me.
Don't concatenate the two queries. Execute the first, save the last id into a variable like
$id = mysqli_insert_id();
, then execute the second query referencing the variable among the values.
Be aware that if those $_POST variables come from a user submitted form it would be useful to do some validation on them before saving them into database. Maybe this answer would be a nice read ;)
I have modify your code. Try and see if it works for you.
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown)VALUES('$Name','$Surname','$Street','$Hometown')";
mysqli_query($con, $sql);
$id = mysqli_insert_id($con);
if ($id) {
$sql = "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES (NULL, NULL, NULL, NULL, NULL, $id)";
mysqli_query($con, $sql);
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
I am learning php and MySql database. I am trying to make payroll management software. In my database both insert & delete operation are executing well but i am facing problem in update operation. Here is my php script :
<html>
<body>
<?php
session_start();
$submit = $_POST['submit'];
$term = $_POST['id'];
//open database
$connect = mysql_connect("localhost","root","#") or die("Couldn't connect");
mysql_select_db("caselab") or die("Couldn't connect");
$sql = mysql_query("SELECT id FROM users WHERE id='$term'");
$count = mysql_num_rows($sql);
if($count!=0)
{
// output data of each row
$id = $_POST['id'];
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$address = strip_tags($_POST['address']);
$contactinfo = $_POST['contactinfo'];
if($submit)
{
//open database
$connect = mysql_connect("localhost","root","#") or die("Couldn't connect");
mysql_select_db("caselab") or die("Couldn't connect");
// Existence Check
if($name && $email && $address && $contactinfo)
{
$queryreg = mysql_query ("Update users SET username = '$name', email = '$email' , address = '$address' , contactinfo = '$contactinfo' WHERE id = $id");
echo ("Congratulations!! Your changes have been saved !! <a href='payroll.html'>Click to go back to home page</a>");
}
else
echo("Please fill all the details");
}
mysql_close($connect);
}
else
echo("No such employee. Please try again.<a href='payroll.html'>Click to go back to home page</a> ");
?>
</html>
</body>
I would be highly thankful if my problem gets resolved.
Why is there a ) before WHERE?
Update users SET username = $name, email = $email , address = $address , contactinfo = $contactinfo) WHERE id = $id");
Try this:
$myqry = "Update users SET username = '". $name."', email = '".$email."' , address = '".$address."', contactinfo = '".$contactinfo."' WHERE id = ".$id.";
echo($myqry;
$queryreg = mysql_query($myqry);
if .....
However, i need reminder you that this is not a good programming method and you need learn how to PDO after you understand the basic query concepts. http://php.net/manual/en/book.pdo.php
I have an issue with my PHP code for a registration form on my website. Some of the code doesn't get executed when the form is submitted.
if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "") {
$con = mysqli_connect("localhost","root","","login")or die("Can't connect to database");
$user = $_POST['user'];
$pass = $_POST['pass'];
$name = $_POST['fname'];
$email = $_POST['email'];
$pwd = crypt('$pass', '$user');
$pwd = md5($pwd);
$tblname = "users";
$flp="INSERT INTO $tblname (Name, Username, Password, Email Address)
VALUES
('$name','$user','$pass','$email')";
$res = mysqli_query($con, $flp)or die("Can't insert to table");
if ($res) {
$complete = "Registered successfully please log in to continue";
} else {
echo "error";
}
}
Everything works fine until it gets to the line starting $flp="INSERT INTO...
Can anyone assist in helping me debug this code, also, please don't link to already written code I want to be able to use this code.
EDIT:
I changed a line to purposely cause an error so I know PHP is reading the line and it does give me the syntax error for the line starting $res=mysqli_...
"Parse error: syntax error, unexpected '$res' (T_VARIABLE) in C:\XamppNew\htdocs\site\regusr.php on line 85"
I removed the semi-colon at the end of the Insert line just to get the error.
EDIT:
I've managed to isolate the problem to the start of the if statement. It seems to be that the line doesn't treat each error as having no content. However, if the error exists it will be displayed on the page next to the form and no such error gets displayed.
Try this:
<?php
//if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "")
//{
// Connect to DB
$mysqli = new mysqli("localhost", "root", "", "login");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Parse Input
$user = $mysqli->real_escape_string($_POST['user']);
$pass = $mysqli->real_escape_string($_POST['pass']);
$pwd = md5(crypt('$pass', '$user'));
$name = $mysqli->real_escape_string($_POST['fname']);
$email = $mysqli->real_escape_string($_POST['email']);
// Insert Record
if ($mysqli->query("INSERT INTO users (`Name`, `Username`, `Password`, `Email Address`) VALUES ('$name', '$user', '$pwd', '$email')")) {
printf ("New user has id %d.\n", $mysqli->insert_id);
} else {
printf("Failed to insert row: %s\n", $mysqli->error);
}
// Close DB Connection
$mysqli->close();
//}
?>
You need to quote (with backticks) your column name Email Address since it has a space in it.
Use backticks in Email Address field because it has space.
$flp="INSERT INTO $tblname (`Name`, `Username`, `Password`, `Email Address`)
Try this ..........
$flp="INSERT INTO $tblname (Name, Username, Password, EmailAddress)
VALUES
('".$name."','".$user."','".$pass."','".$email."')";
I have a 'registration' page in PHP and I would like the script to run when an HTML button is clicked.
The PHP basically checks if all fields are filled, checks if the password and email confirmations are the same and saves to the database.
This is the code:
<?php
$Name = isset($_POST['Name']);
$Surname = isset($_POST['Surname']);
$Username = isset($_POST['Username']);
$Email = isset($_POST['Email']);
$C_Email = isset($_POST['C_Email']);
$Password = isset($_POST['password']);
$C_Password = isset($_POST['c_password']);
$SecQ = isset($_POST['SecQ']);
$SecA = isset($_POST['SecA']);
$con = mysql_connect('localhost', 'admin', 'storefile1234');
mysql_select_db ("storefile");
$check_username = mysql_query("SELECT FROM users WHERE username = '$Username'");
$check_email = mysql_query("SELECT FROM users WHERE Email = '$Email'");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if ($Name == null || $Surname== null || $Username == null || $Password == null || $C_Password == null || $Email == null || $C_Email == null || $SecQ == null || $SecA == null ) {
echo "Missing details. Please enter all fields.";
} else {
if(mysql_num_rows($check_username) != 0 && mysql_num_rows($check_email) != 0)
{
echo "Username/Email already exists";
}
if ($Email == $C_Email && $Password == $C_Password) {
$query = "INSERT INTO users (Username, Name,Surname, Password, Email, SecQ, SecA) VALUES ('NULL', ".$Username."', ".$Name."', ".$Surname."', ".$Password."', ".$SecQ."', ".$SecA."', ".$Email.')"';
mysql_query($query) or die ('Error registering.');
echo "Greetings, ".$Name.", you have been registered. ";
} else {
echo "Error registering your account. Please try again.";
}
}
?>
Also, is it recommended?
Whenever I run this page Missing details. Please enter all fields. displays, without having entered any details.
How do you do this?
You tying to get values by isset($_POST['Username']); and like this functions...
But documentation says: Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
So check on true, nut null. And escape your POST data after.
You can do like this:
$Name = isset($_POST['Name']) ? mysql_real_escape_string($_POST['Name']) : null;
P.S. Please again. Do not use mysql_* function. They are DEPRECATED.
Look on PDO (or mysqli_*)
For the issue of printing that message when you first load the page, use the array_key_exists function to test if the user has already submited something before checking if any field is null. Something like this:
if (array_key_exists('Name', $_POST) || array_key_exists('Surname', $_POST) || ... )
if ($Name == null || $Surname== null || ... )
echo "Missing details. Please enter all fields.";
Observation: you cannot use the isset function for the same purpose since, according to php documentation, it "determine if a variable is set and is not NULL"
You misuse isset
Try something like this:
$Name = null;
if (isset($_POST['Name'])) {
$Name = $_POST['Name'];
}
isset is only to check if a value is set.