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);
}
Related
I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}
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();
This is my code, we have database called "our_new_database".
The connection is fine, as well as the HTML Form and credentials and I still cannot insert information into the database.
Table is created, I can see the columns and lines in XAMPP / phpMyAdmin.
The only error I'm getting is the last echo of the If/Else Statement - "Could not register".
Tried everything I can and still cannot make this insertion to work normally.
Can someone advise me something?
<?php
include "app".DIRECTORY_SEPARATOR."config.php";
include "app".DIRECTORY_SEPARATOR."db-connection.php";
include "app".DIRECTORY_SEPARATOR."form.php";
$foo_connection = db_connect($host, $user_name, $user_password, $dbname);
$sql = "CREATE TABLE user_info(
user_name_one VARCHAR(30) NOT NULL,
user_name_two VARCHAR(30) NOT NULL,
user_email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($foo_connection, $sql)){
echo "Table created successfully";
}
else {
echo "Error creating table - table already exist.".mysqli_connect_error($foo_connection);
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$user_name_one = $_POST["userOne"];
$user_name_two = $_POST["userTwo"];
$user_email = $_POST["userEmail"];
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
if(mysqli_query($foo_connection,$sql))
{
echo "Successfully Registered";
}
else
{
echo "Could not register";
}
}
$foo_connection->close();
You should avoid the direct use of variables in SQL statements, instead, you should use parameterized queries.
This also should avoid the need to string concatenation and manipulation problems.
$stmt = $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$stmt->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$stmt->execute();
You need to change
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
To
$sql = "INSERT INTO `user_info`(`user_name_one`,`user_name_two`,`user_emai`l) VALUES ('$user_name_one','$user_name_two','$user_email')";
remember you should use prepared query
$sql= $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$sql->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$sql->execute();
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
I reckon your parentheses on this line:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
Do not match, it should look like something like this:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
Cause for know your query is:
"INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('value',('value1',('value2')"
As said above you might use:
echo $foo_connection->error
To see some errors displayed
I am creating an edit profile page where the logged in user can edit the profile. I now run into the error below. what do i do?
ERROR:
Database Connection FailedYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= 'test#hotmail.com', Password = 'test', FirstName = 'hello', SecondName = 'world' at line 1
My code:
<?php
$connection = mysqli_connect('localhost', 'root', '', 'dbrateme');
if (!$connection){
die("Database Connection Failed" . mysql_error());
header('Location: dcf.php');
}
$select_db = mysqli_select_db($connection, 'dbrateme');
if (!$select_db){
die("Database Selection Failed" . mysqli_error());
}
if (isset($_POST['upd'])){
$course = $_POST['Course'];
$email = $_POST['inputEmail'];
$password = $_POST['inputPassword'];
$FN = $_POST['FirstName'];
$SN = $_POST['SecondName'];
$qsql = $_COOKIE['userID'];
$qresult = mysqli_query($connection, $qsql);
$qcount = mysqli_connect($qresult);
$sqli = "UPDATE tblaccounts Email = '".$email."', Password = '".$password."', FirstName = '".$FN."', SecondName = '".$SN."', Course = '".$course."' WHERE Student_ID='".$qsql."'";
$result = mysqli_query($connection, $sqli) or die("Database Connection Failed" . mysqli_error($connection));
//$count = mysqli_num_rows($result);
echo "Profile Update Successful!:";
header('Location: profile.php');
} else {
echo "Profile Update Failed!:";
?><br/>Go back to the profile update screen.<?php
}
?>
You miss the keyword set in your SQL. Syntax for Update is UPDATE <table> SET <colum Name> = value
$sqli = "UPDATE tblaccounts SET Email = '".$email."', Password = '".$password."', FirstName = '".$FN."', SecondName = '".$SN."', Course = '".$course."' WHERE Student_ID='".$qsql."'";
Learn about prepared stateemnts to prevent SQL injection.
Never store passwords as plain text. Use function to encrypt them
The issue is with the query, but my god are you open to a serious case of sql injection. To target the first issue.
UPDATE tblaccounts Email
Change this to
UPDATE tblaccounts SET Email
The query you are using is vulnerable to sql injection. You should fix this as soon as possible. I would suggest using PDO prepared statements for all of your SQL queries. http://php.net/manual/en/book.pdo.php
I did 2 tables in mysql database
user_details
bank_details
In user_details am create following entity
user_id as a Primary Key
username
password
address
In bank_details am create following entity
id as a Primary Key
user_id as a Foreign Key
bank_name
ac_no
First am insert user details using following code
<?php
$un = $_POST['un'];
$ps = $_POST['ps'];
$adr = $_POST['adr'];
$sql = mysql_query("insert into user_details username='$un', password='$ps', address='$adr'");
?>
Now i need to insert Bank Details in bank_details table
<?php
$bn = $_POST['bn'];
$ac_no = $_POST['ac'];
$sql = mysql_query("insert into bank_details user_id= ?? bank_name='$bn', ac_no='$ac_no'");
?>
How can i define that foreign key values here ?
Your query omits the MYSQL SET keyword. Anyway, you can do this, as per your code convention:
<?php
$mysql = mysql_connect([...]
$un = mysql_real_escape_string($_POST['un'], $mysql);
$ps = mysql_real_escape_string($_POST['ps'], $mysql);
$adr = mysql_real_escape_string($_POST['adr'], $mysql);
$sql = mysql_query("insert into user_details SET username='$un', password='$ps', address='$adr'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysql_insert_id(); //get the id of the last inserted query/user
$bn = mysql_real_escape_string($_POST['bn'], $mysql);
$ac_no = mysql_real_escape_string($_POST['ac'], $mysql);
$sql = mysql_query("insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
I must point out, however, that using the mysql_* family of functions is deprecated, and you should seriously start using mysqli_* functions instead.
UPDATE:
As Per CodeGodie's suggestion, here's the re-written code using mysqli_* functions:
<?php
$mysqli = mysqli_connect(SERVER_NAME, USER_NAME, PASSWORD, DB_NAME);
$un = mysqli_real_escape_string($_POST['un']);
$ps = mysqli_real_escape_string($_POST['ps']);
$adr = mysqli_real_escape_string($_POST['adr']);
$sql = mysqli_query($mysqli, "insert into user_details SET username='$un', password='$ps', address='$adr'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysqli_insert_id($mysqli); //get the id of the last inserted query/user
$bn = mysqli_real_escape_string($_POST['bn']);
$ac_no = mysqli_real_escape_string($_POST['ac']);
$sql = mysqli_query($mysqli, "insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>