I am having trouble with PHP and MYSQL. I have an HTML form which when submitted runs the following PHP script.The problem is that the following PHP code is inserting the data into the database twice. I think it is something to do with the following PHP and not the database:
<?php
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$display_name = $_POST['displayname'];
$email = $_POST['email'];
$password = $_POST['password'];
$add_line1 = $_POST['addline1'];
$add_line2 = $_POST['addline2'];
$city = $_POST['city'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
$sql = "INSERT INTO members (memberID,
memberPassword,
memberFirstName,
memberLastName,
memberAddressLine1,
memberAddressLine2,
memberCity,
memberCounty,
memberPostcode,
memberDisplayName)
VALUES ('$email',
'$password', '$first_name', '$last_name',
'$add_line1', '$add_line2','$city',
'$county', '$postcode', '$display_name')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
echo 'Guest Added';
mysqli_close($conn);
?>
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
You have mysqli_query($conn,$sql); in your code twice. Once in the if(), and once outside. Each of these will insert into your database.
The point to note here is that the mysqli_query inside the if is evaluated - that is, it is run and the if statement executes on the result of the function call. Thus, you do not need to call it again.
Tushar pointed out the twin mysqli queries and he is right, besides that, the code as is now will cause you security troubles since it allows sql injection...
Please modify your code as follows:
$first_name = mysqli_escape_string($conn, $_POST['firstname']);
$last_name = mysqli_escape_string($conn, $_POST['lastname']);
$display_name = mysqli_escape_string($conn, $_POST['displayname']);
$email = mysqli_escape_string($conn, $_POST['email']);
$password = mysqli_escape_string($conn, $_POST['password']);
$add_line1 = mysqli_escape_string($conn, $_POST['addline1']);
$add_line2 = mysqli_escape_string($conn, $_POST['addline2']);
$city = mysqli_escape_string($conn, $_POST['city']);
$county = mysqli_escape_string($conn, $_POST['county']);
$postcode = mysqli_escape_string($conn, $_POST['postcode']);
Related
I am wanting to keep a table log history of executed MySQLI queries and log the specific user who executed a query and date & time the query was executed - on any (all) of my PHP pages.
What is the best way and simplest way to achieve this?
PHP
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
$connection = mysqli_connect("****", "****", "****", "****");
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error());
}
if(isset($_POST['update'])) {
$accountNo = $_GET['ID'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$town = $_POST['town'];
$postcode = $_POST['postcode'];
Recommendation from a SO user:
However, there are errors with this suggestion ...many.
$query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";
$log_action = mysqli_query($connection,$query);
$result = mysqli_query($connection,$query);
if($result) {
define("LOG_FILE", "https://www.*******.com/logfile.txt");
function log_action($action, $data) {
$time = date('Y-m-d h:i:s');
$user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
$message = "$time\tuser=$user\taction=$action\tdata=$data\n";
file_put_contents(LOG_FILE, $message, FILE_APPEND);
}
Write a wrapper library that logs all the mysqli calls that you want to record, e.g.
function my_mysqli_query($link, $query, $resultmode = MYSQLI_STORE_RESULT) {
log_action('mysqli_query', $query);
return mysqli_query($link, $query, $resultmode);
}
function my_mysqli_prepare($link, $query) {
log_action('mysqli_prepare', $query);
return mysqli_prepare($link, $query);
}
...
define("LOG_FILE", "/path/to/logfile.txt");
function log_action($action, $data) {
$time = date('Y-m-d h:i:s');
$user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
message = "$time\tuser=$user\taction=$action\tdata=$data\n";
file_put_contents(LOG_FILE, $message, FILE_APPEND);
}
I've written it to log to a file. You could log to a database table instead, it's just more code in log_action().
Then do a global replace in all your other scripts, replacing mysqli_query with my_mysqli_query, mysqli_prepare with my_mysqli_prepare, and so on. So your code would look like:
if(isset($_POST['update'])) {
$accountNo = $_GET['ID'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$town = $_POST['town'];
$postcode = $_POST['postcode'];
$query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";
$result = my_mysqli_query($connection,$query);
if ($result) {
echo "Update successful";
}
}
I was facing some problems with my database code. I used an insert query to insert my data from the form into my database called "wstorage". Only this method didn't work when I used the usual query " INSERT INTO users (nom, Prenom,..) VALUES ('$nom', '$Prenom'..).
In fact, the query did work but nothing showed on my database. Then I used another query where I call for the second time the name of my database 'wstorage'(the first time being in the session start and connection) and suddenly it works.
My question is : Why does it work when I normally don't have to call my database in the insert query?
This is my server.php code :
<?php
session_start();
$db = mysqli_connect('localhost','root','','wstorage');
if (mysqli_connect_errno()) {
echo 'Failled to connect to MYSQL: '.$mysqli_connect_errno();
}
// REGISTER USER
if (isset($_POST['registeruser'])) {
// receive all input values from the form
$nom = mysqli_real_escape_string($db, $_POST['nom']);
$Prenom = mysqli_real_escape_string($db, $_POST['Prenom']);
$Situation = mysqli_real_escape_string($db, $_POST['Situation']);
$sex = mysqli_real_escape_string($db, $_POST['sex']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$Nombre_Livre = mysqli_real_escape_string($db, $_POST['Nombre_Livre']);
$Nombre_Media = mysqli_real_escape_string($db, $_POST['Nombre_Media']);
$Nombre_Recidives = mysqli_real_escape_string($db, $_POST['Nombre_Recidives']);
$Etat_Abon = mysqli_real_escape_string($db, $_POST['Etat_Abon']);
$Penalite = mysqli_real_escape_string($db, $_POST['Penalite']);
$Etat_Penalite = mysqli_real_escape_string($db, $_POST['Etat_Penalite']);
$Numero = mysqli_real_escape_string($db, $_POST['Numero']);
$query = "INSERT INTO `wstorage`.`users` (`nom`, `Prenom`, `Situation`, `sex`, `email`, `Numero`, `Nombre_Livre`, `Nombre_Media`, `Nombre_Recidives`, `Etat_Abon`, `Penalite`, `Etat_Penalite`, `date`) VALUES ('$nom', '$Prenom', '$Situation', '$sex', '$email', '$Numero', '$Nombre_Livre', '$Nombre_Media', '$Nombre_Media', '$Etat_Abon', '$Penalite', '$Etat_Penalite', CURRENT_TIMESTAMP)";
mysqli_query($db, $query);
if($query) {
echo "success";
} else {
echo " Fail";
}
}
?>
I am a novice trying to do the site for a non profit I volunteer with. Most of the code was gleened from You tube. Below is the code. The db name is cani the table is contact. When ever I submit is doesn't give me a success message, no data shows up in the database, and it doesn't return back to newentry.php. My brain hurts!
<?php
if (isset($_POST['submit'])){
include_once('dbh.inc.php');
$type = mysqli_real_escape_string($conn, $_POST['type']);
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$company = mysqli_real_escape_string($conn, $_POST['company']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$add1 = mysqli_real_escape_string($conn, $_POST['add1']);
$add2 = mysqli_real_escape_string($conn, $_POST['add2']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$state = mysqli_real_escape_string($conn, $_POST['state']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$sql = "INSERT INTO contact (contact_type, contact_first, contact_last, contact_company, contact_email, contact_phone, contact_add1, contact_add2, contact_city, contact_state, contact_zip) VALUES ('$type', '$first', '$last', '$company', '$email', '$phone', '$add1', '$add2', '$city', '$state', '$zip')";
mysqli_query($conn, $sql);
header("Location: ../newentry.php?Success!");
}else{
header("Location: ../index.html");
exit();
}
?>
Grr I partially fixed it...now everything works, except nothing is showing up in the database...it is connecting, I made sure the table name is correct. It says success. But whe I open phpAdmin and open the table, it is blank.
Check if the variable $_POST['submit'] exists
Is this code prone to SQL Injection? Can you suggest something to improve the security? Is it right to use mysqli_real_escape_string? And do you think it's alright to use this for project?
<?php
require 'db.php';
if(isset($_POST['pawnshopName'])&&isset($_POST['street'])&&isset($_POST['barangay'])&&isset($_POST['city'])&&isset($_POST['dtiPermitNo'])&&isset($_POST['mayorPermitNo'])&&isset($_POST['firstName'])&&isset($_POST['lastName'])&&isset($_POST['middleName'])&&isset($_POST['contactNumber'])&&isset($_POST['email'])&&isset($_POST['password'])&&isset($_POST['confirmPassword']))
{
$options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),];
$pawnshopName = mysqli_real_escape_string($connection, $_POST['pawnshopName']);
$street = mysqli_real_escape_string($connection, $_POST['street']);
$barangay = mysqli_real_escape_string($connection, $_POST['barangay']);
$city = mysqli_real_escape_string($connection, $_POST['city']);
$dtiPermitNo = mysqli_real_escape_string($connection, $_POST['dtiPermitNo']);
$mayorPermitNo = mysqli_real_escape_string($connection, $_POST['mayorPermitNo']);
$firstName = mysqli_real_escape_string($connection, $_POST['firstName']);
$lastName = mysqli_real_escape_string($connection, $_POST['lastName']);
$middleName = mysqli_real_escape_string($connection, $_POST['middleName']);
$contactNumber = mysqli_real_escape_string($connection, $_POST['contactNumber']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, password_hash($_POST['password'], PASSWORD_BCRYPT, $options));
$confirmPassword = mysqli_real_escape_string($connection, $_POST['confirmPassword']);
if(password_verify($confirmPassword,$password))
{
echo 'Password Match';
}else
{
echo 'Password mismatch';
}
$sql = "INSERT INTO pawnshop ".
"(Pawnshop_ID, Pawnshop_Name, Street, Barangay, City, DTI_Permit_No, Mayor_Permit_No, Firstname, Middlename, Lastname, Contact_Number, Email_Address, Password) ".
"VALUES ".
"('','".$pawnshopName."', '".$street."', '".$barangay."', '".$city."', '".$dtiPermitNo."', '".$mayorPermitNo."', '".$firstName."', '".$lastName."', '".$middleName."', '".$contactNumber."', '".$email."', '".$password."' )";
mysqli_query($connection, $sql);
mysqli_close($connection);
}
?>
No, you must use prepare method. Then on every place where you want to add a value place a ?. Than you must use the bind_param method. Finally, you can execute it and get the results whit get_results. An example:
$stmt = $connection->prepare("INSERT INTO Customers (CustomerName, Address, CityID) VALUES (?, ?, ?)");
$stmt->bindParam('ssi', $name, $address, $cityId);
$stmt->execute();
$results = $stmt->get_results();
The 'ssi' are corresponding variable the types of the attributes.
i are integers
d are doubles
s are strings
b is a blob and will be sent in packets
My resources are: w3schools and php.net
So I am creating a forum and currently working on the sign up script. I have the sign up form in the signup.php page and the processing part in the signup_process.php
I have an issue where only a current user is able to sign up a new user when they are signed in, any suggestions on how to fix this. I am not able to sign up a new user when I am not logged in as a current one.
Below is my signup_process.php page:
<?php
include "includes/pagetop.php";
include "includes/header.php";
include "includes/nav.php";
?>
<?php
$_SESSION['username'] = $_POST['username'];
$_SESSION['fname'] = $_POST['fname'];
$_SESSION['surname'] = $_POST['surname'];
$_SESSION['dob'] = $_POST['dob'];
$_SESSION['emailaddress'] = $_POST['emailaddress'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['gender'] = $_POST['gender'];
$_SESSION['city'] = $_POST['city'];
$_SESSION['sports'] = $_POST['sports'];
$username = $_POST['username'];
$fname = $_POST['fname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$city = $_POST['city'];
$query = "INSERT INTO user
(
user_username,
user_firstname,
user_surname,
user_dob,
user_email,
user_password,
user_gender,
user_city,
user_active
)
VALUES(
'".$_POST['username']."',
'".$_POST['firstname']."',
'".$_POST['surname']."',
'".$_POST['dob']."',
'".$_POST['email']."',
'".$_POST['password']."',
'".$_POST['gender']."',
'".$_POST['city']."',
'1'
) ";
mysql_query($query) or die (mysql_error());
$lastid = mysql_insert_id();
$sports = $_POST['sports'];
foreach ($sports as $key => $value){
$query2 = " INSERT INTO usersport
(
usersport_user_id,
usersport_sport_id
)
VALUES(
'".$lastid."',
'".$value."'
)";
mysql_query($query2) or die (mysql_error());
}
?>
If you are talking about inserting duplicate users, you could solve this making on the database a primary key on username and an unique index on emailaddress.
If you are talking about the sign up page being served while a user is currently authenticated, you could create a session variable that is set to true when the current user authenticates into the system. Them you could check if this variable is false to serve the sign up page, or give a error otherwise.
And you have a sql injection vulnerability in your code, you should consider using prepared statements instead of plain text.