I have three files reg_form.php, dbconnection.php and insert.php.
When submitting the form the data is not inserted into the database. I can't figure out why. Initially I didn't know how to use insert into multiple tables but took the advice of many posts from here. Unfortunately I have still failed to make it work and it is driving me insane. Here is the sql code so far for the insert.
<?php
include ("dbconnection.php");
if(file_exists("dbconnection.php")) {
echo"Connected to database successfully";
} else if(!file_exists("dbconnection.php")){
echo "Connection failed";
}
$forename = "forename";
$surname = "surname";
$address_line1 = "address_line1";
$address_line2 = "address_line2";
$address_line3 = "address_line3";
$city = "city";
$postcode = "postcode";
$phone = "phone";
$email = "email";
$username = "username";
$password = "password";
$cpassword = "cpassword ";
$query = "INSERT INTO users (username,
password)VALUES('$username','$password');";
$query2 = "INSERT INTO users_details (forename, surname,address_line1,
address_line2, address_line3, city, postcode, phone, email)
VALUES('$forename','$surname','$address_line1','$address_line2',
'$address_line3','$city','$postcode','$phone','$email')";
query ($dbconnection,$sql);
?>
Ok problem is solved. I made a stored procedure because I am doing an INSERT INTO multiple tables and then called it like this.
$sql ="CALL add_user('".$username."', '".$password."', 'user',
'".$forename."','".$surname."', '".$address_line1."' ,
'".$address_line2."', '".$address_line3."', '".$city."', '".$postcode."',
'".$phone."', '".$email."','".is_bool($email_contact)."',
'".is_bool($phone_contact)."')";
$query = $con->prepare($sql);
$query->execute();
Related
Hi I have a form where a teacher can create a new school as a user and that teacher's school gets an ID. So I check the database to make sure the id doesn't already exist in the "school" table. If it does I get that school ID so the teacher can create a profile with it. If it doesn't already exist then a new one is created and entered into both the "school" table AND the "users" table for that teacher's school.
It's working fine, only except that every time the form is filled out the data is entered twice, but only in the "USERS" table. In the "school" table it is entered once as it should be.
Can someone tell me why this is happening? I have been looking for weeks.
code:
if(isset($_POST['submit'])){
$name=$_POST['name'];
$name = mysqli_real_escape_string($con,$name);
$lastname=$_POST['lastname'];
$lastname = mysqli_real_escape_string($con,$lastname);
$email=$_POST['email'];
$email = mysqli_real_escape_string($con,$email);
$phone=$_POST['phone'];
$phone = mysqli_real_escape_string($con,$phone);
$school=$_POST['school'];
$school = mysqli_real_escape_string($con,$school);
$address=$_POST['address'];
$address = mysqli_real_escape_string($con,$address);
$region=$_POST['region'];
$region = mysqli_real_escape_string($con,$region);
$state=$_POST['state'];
$state = mysqli_real_escape_string($con,$state);
$zip = $_POST['zip'];
$zip = mysqli_real_escape_string($con,$zip);
$password= $_POST['password'];
$hash = password_hash($password, PASSWORD_BCRYPT);
//GET STATE NAME
$getState = "SELECT state from `states` WHERE id= '$state'";
$stateRes = mysqli_query($con, $getState);
$stateRow = mysqli_fetch_array($stateRes);
$stateName = $stateRow['state'];
//CHECK SCHOOL
$checkSchool = "SELECT school from `schools` WHERE school= '$school'";
$schoolRes = mysqli_query($con, $checkSchool);
$schoolCount = mysqli_num_rows($schoolRes);
if($schoolCount >0){
//if school exist get it's id
$schoolIdSql = "SELECT id from `schools` WHERE school= '$school'";
$schoolIdRes = mysqli_query($con, $schoolIdSql);
$schoolRow = mysqli_fetch_array($schoolIdRes);
$schoolId = $schoolRow['id'];
}else{
//if doesn't exist insert new school
$schoolquery = "INSERT INTO schools (state_id, school) VALUES ('$state','$school')";
$schoolresult = mysqli_query($con, $schoolquery);
//get new school id
$schoolIdSql = "SELECT id from `schools` WHERE school= '$school'";
$schoolIdRes = mysqli_query($con, $schoolIdSql);
$schoolRow = mysqli_fetch_array($schoolIdRes);
$schoolId = $schoolRow['id'];
}
//CHECK USER
$checkUser = "SELECT email from `Users` WHERE email= '$email'";
$userRes = mysqli_query($con, $checkUser);
$userCount = mysqli_num_rows($userRes);
if($userCount >0){
$submitted = "Email is not available";
$invalid = '<input id="email" type="text" name="email" class="form-control is-invalid" required="required" data-error="email is required." data-remote="/validate">';
} else{
$userId = rand(1,9999999);
$check_userId ="select count(*) count from Users where user_id = " . $userId;
while ($row['count'] > 0);
$query = "INSERT INTO Users (id, user_type, name, lastname, email, phone, school, address, state, zip, password, status) VALUES ('$userId','teacher','$name', '$lastname', '$email', '$phone', '$schoolId', '$address', '$stateName', '$zip', '$hash', 'active')";
$result = mysqli_query($con, $query);
if(!$result = $con->query($query)){
die('there was an error running query [' . $con->error . ']');
}else {
header("location: thankyou");
}
}
}
It seems some old artefacts of earlier programming survived:
Maybe this is the new query:
$result = mysqli_query($con, $query);
And maybe this is the old one?
if(!$result = $con->query($query))
Should do the same and be the cause for the duplicate of the insert.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
Please find my code below:
<?php
//Insert New User to Database
$username = "root";
$password = "root";
$hostname = "localhost";
$db = "ab-cargo";
$conn = mysqli_connect($hostname, $username, $password, $db);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_SESSION['namechat'];
$user_email = $_SESSION['emailchat'];
$last_login = $datetime_formatted;
mysqli_query($conn,"INSERT INTO users (`user_id`, `user_email`, last_login, isActive) VALUES ('".$user_id."', '".$user_email."', '".$last_login."', 1)");
mysqli_query($conn,"UPDATE users SET last_login = ".$last_login.", isActive = 1 WHERE `user_email` = ".$user_email."");
?>
Please help me to find what's wrong with mysqli_query because it won't update and insert the data in my database, even though the connection is finely working (I know it because user is able to login).
Edit: Query insert is to input new user data into the database and if the user data is already in the database before, the update query will update last_login time/date only.
You need to prevent MySQL injection with mysqli_real_escape_string. Read up more about this function here.
Use or die mysqli_error($conn) to check for errors in query.
Also, check if each query is successful before proceeding to the next one.
$user_id = mysqli_real_escape_string($conn, $_SESSION['namechat']);
$user_email = mysqli_real_escape_string($conn, $_SESSION['emailchat']);
$last_login = mysqli_real_escape_string($conn, $datetime_formatted);
$query1 = mysqli_query($conn,"INSERT INTO users (`user_id`, `user_email`, last_login, isActive) VALUES ('$user_id', '$user_email', '$last_login', 1)") or die mysqli_error($conn);
if ($query1) $success = 1;
if ($success) $query2 = mysqli_query($conn,"UPDATE users SET last_login = '$last_login', isActive = 1 WHERE `user_email` = '$user_email'");
if ($query2) echo 'User added';
$_SESSION['namechat']= "1";
$_SESSION['emailchat']= "example#gmail.com";
//SET DATE TIME ZONE
date_default_timezone_set("Asia/Calcutta");
$datetime_formatted = date("h:i:sa");
$user_id = $_SESSION['namechat'];
$user_email = $_SESSION['emailchat'];
$last_login = $datetime_formatted;
//HERE INSERT THE DATA INTO USER
$sql = "INSERT INTO users (user_id, user_email, last_login, isActive) VALUES ('$user_id', '$user_email', '$last_login', '1')";
if(mysqli_query($conn,$sql)){
echo "sql inserted successfully";
}
else
{
echo "failed to insert".$sql."<br>".mysqli_error($conn);
}
//HERE UPDATE THE DATA INTO USER
$sql_up ="UPDATE users SET last_login ='$last_login', isActive = '1' WHERE user_email = '$user_email'";
if(mysqli_query($conn, $sql_up)){
echo "Data Updated";
}
else
{
echo "Failed to Updated the data".$sql_up."<br>".mysqli_error($conn);
}
I'm trying to update data in my database with this function
<?php
require "conn.php";
$name = $_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$mysql_qry = "UPDATE user_data (name, surname, age, username, password) values ('$name','$surname','$age','$username','$password')";
if($conn->query($mysql_qry) === TRUE) {
echo "Success!";
}
else {
echo "Something is wrong :( Error: " . $mysql_qry . "<br>" . $caonn->error;
}
$conn->close();
but it always goes to Error. Can you help me with this? I was trying to put data from keyboard but it's not working either.
I've changed this line
$mysql_qry = "UPDATE user_data SET name = '$name'";
and now it's working but its changing all the names in database and I want to change only one record...
Add WHERE id=THAT_ID and you will be fine. THAT_ID or 'THAT_ID' depending on whether the "id" field in the database is a number or text, respectively (without apostrophes if it's a number, and with apostrophes if it is a text field). Off course, change THAT_ID to whatever id you want.
My code is showing -1 Record Inserted error and not inserting the fields to database. Any thoughts of why is it doing this?
<?php
include("dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
if($_POST) {
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
$users_name = htmlspecialchars($users_name);
$users_email = htmlspecialchars($users_email);
$users_website = htmlspecialchars($users_website);
$users_comment = htmlspecialchars($users_comment);
$postid = $_GET['id'];
$sSql = "INSERT INTO comments
( post_id, name, email, website,content)
VALUES ($postid, '$users_name',
'$users_email', '$users_website', '$users_comment' )";
mysql_query($sSql);
$update=mysql_affected_rows();
echo "<h2>$update Record Inserted</h2><br />";
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
For some reason, the comments table is not getting updated. I am new to programming in mySQL and PHP. Any suggestions would be of so much help to me. Thanks.
First insert dummy values in your php SQL statement & comment mysql_query statement.
$sSql = "INSERT INTO comments (post_id,name,email,website,content) VALUES (100, 'anoop.pete','anoop.pete#gmail.com', 'www.anooppete.com', 'Nice Website' )";
//mysql_query($sSql);
//$update=mysql_affected_rows();
Print the SQL statement...
print($sSql);
Copy the SQL statement from web browser, Execute the $sSql in MySql
If the row is inserted, in MySQL, uncomment and run the same page again.
mysql_query($sSql);
$update=mysql_affected_rows();
If it runs, try removing htmlspecialchars()
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
I guess your htmlspecialchars() is returning some invalid characters...
-1 means the query returned an error.
Put this sql query into your sql browser's sql 'querier' and see what the error is:
INSERT INTO
comments
(post_id,
name,
email,
website,
content)
VALUES
(2,
'name',
'email#',
'http://',
'comment')
I'm very new to PHP and am having some trouble. I have a form using HTML which is action=.php method=post
The form is using text boxes and select options, I'm not sure if it makes a difference in sqldatabase. I've tried about 30 different combinations of this script and can only get a connect successfully message but nothing is posted.
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user");
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
mysql_close();
php?>
try to execute your query
mysql_query($sql);
EDIT: I see you are doing this:
$sql = 'SELECT bla bal $variable';
PHP will not parse the variable. The right way:
$sql = "SELECT bla bla $variable"; // valid
$sql = "SELECT bla bla {$variable}"; // also valid
$sql = 'SELECT bla bla '.$variable; // also valid
your closing php tag is not correct, it should be
?>
rather than
php?>
Also u r not executing your query using:
mysql_query('your query here');
this might cause the problem.
Your variables are not interpreted by PHP. If you want variable to be parsed in string, it should be wrapped in double-quote (")
It may fail if any of your posted data contains some quote character, so you must apply mysql_real_escape_string to all of them.
I hope that database connection credentials are not real you posted here? :D
You said that your form contains "action=.php" literally, you have to turn it into :
<form name="form_name" method="post" action="your_script.php">
You need to execute the query too:
mysql_query($sql, $link);
you should also check whether POST was really sent:
if (!empty($_POST)) {
// ... your code here
}
next thing: you don't need closing tag ?> if your *.php file consist only PHP code - end of file is also correct end of PHP block of code - it's "good-to-have" habit, because in some cases it helps you to avoid error: "Cannot add/modify header information - headers already sent by..."
next problem - wrong way of inserting variables into string:
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
correct way:
$sql = "INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES (null, '$FName', '$LName', '$Phone', '$EmailAddress', '$Month', '$Day', '$Year', '$Username', '$Password')";
more info here
next - as Deniss said, instead of:
$FName = $_POST["FName"];
should be:
$FName = mysql_real_escape_string($_POST["FName"]);
actually you should fist check weather magic quotes gpc are on or off:
if (get_magic_quotes_gpc()) {
if (!empty($_POST)) {
array_walk_recursive($_POST, 'stripslashes_value');
}
}
function stripslashes_value(&$value) {
$value = stripslashes($value);
}
without this you could have problem with double \\ inserted into db (it depends on your server configuration)
and last but not least: as Robert said you miss one more important thing:
mysql_query($sql);
I think your error because your have not call mysql_query function
can try my code edit
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user",$link);
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = "INSERT INTO Members SET FName='{$FName}', LName='{$LName}', Phone='{$Phone}', EmailAddress='{$EmailAddress}', Month='{$Month}', Day='{$Day}', Year='{$Year}', Username='{$Username}', Password='{$Password}'";
// Call Function mysql_query insert new record in mysql table
mysql_query($sql,$link);
mysql_close($link);
?>
Comment for me if your have problem :) or notes of apache services
good day