Hey.. I'm a bit stuck on PHP code to insert data into multiple SQL tables. I an unable to get the data into both tables within a single action. This is for a registration page to create a user login and start of company profile. Any suggestions would be much appreciated. Thanks
<?php
session_start();
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
include_once 'resources/php/dbconnect.php';
if(isset($_POST['btn-signup']))
{
$uname = mysql_real_escape_string($_POST['uname']);
$email = mysql_real_escape_string($_POST['email']);
$upass = md5(mysql_real_escape_string($_POST['pass']));
$orgname = mysql_real_escape_string($_POST['orgname']);
$uname = trim($uname);
$email = trim($email);
$upass = trim($upass);
$orgname = trim($orgname);
// email exist or not
$query = "SELECT user_email FROM users WHERE user_email='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result); // if email not found then register
if($count == 0){
if(mysql_query("START TRANSACTION;
INSERT INTO users('user_name','user_email','user_pass')
VALUES('$uname','$email','$upass');
INSERT INTO companies('name','owner_id')
VALUES('$orgname','$email');
END;"))
{
?>
<script>alert('Registration Successful');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
else{
?>
<script>alert('Sorry Email ID already taken ...');</script>
<?php
}
}
?>
As you can see here the mysql extension is deprecated and you MUST stop using it. Great alternatives are PDO and mysqli
You should also use Prepared Statements to safeguard your code against SQL Injection attacks.
To complete a Transaction using PDO you can do this:
$conn->query("START TRANSACTION");
$stmt = $conn->prepare("INSERT INTO users(user_name,user_email,user_pass) VALUES(?,?,?)");
try
{
$stmt->bindValue(1,$user_name);
$stmt->bindValue(1, $user_email);
$stmt->bindValue(3, $user_pass);
$stmt->execute();
$secondStmt = $conn->prepare("INSERT INTO companies(name,owner_id) VALUES(?,?)");
$secondStmt->bindValue(1, $name);
$secondStmt->bindValue(2, $owner_id);
$secondStmt->execute();
$conn->query("COMMIT"); //This commits all changes if no error occured
}
catch(Exception $e)
{
$conn->query("ROLLBACK"); //This reverts any changes made in case of an error
}
You can do two inserts like this:
$queryUsers = INSERT INTO users('user_name','user_email','user_pass')
VALUES('$uname','$email','$upass');
mysql_query($queryUsers);
$queryCompanies = INSERT INTO companies('name','owner_id')
VALUES('$orgname','$email');
mysql_query($queryCompanies);
In addition, carefully with mysql_query, is deprecated, try to use mysqli().
Regards
Related
Here's a well known example how to prevent sqlinjection. There are two files like login.php and profile.php But it doesn't do anything with ether entering a correct login and pass or incorrect data. Doesn't echo about any case. SQL server goes by MAMP.
Here's the code:
<?php
$con = new mysqli("localhost", "root", "root", "phpsec");
if ($con->connect_error){
echo $con->connect_error;
}
if (isset($_POST["submit"])) {
$pre_stmt = $con->prepare("SELECT * FROM userinfo WHERE email = ? AND pass = ?");
$pre_stmt->bind_param("ss",$_POST["email"],$_POST["pass"]);
$pre_stmt->execute();
$result = $pre_stmt->get_result();
if($result->num_rows > 0){
$row = $result->fetch_assoc();
header("location:profile.php?email=".$row["email"]);
} else{
echo "login fail";
}
}
?>
and profile.php:
<?phpecho "Welcome ".$_GET["email"]; ?>
What and where did I do wrong?
you can prevent your page from sql injection using prepared statement in php
try this code in while performing sql statements.
<?php
// prepare and bind
$stmt = $conn->prepare("INSERT INTO example(firstname, lastname, email) VALUES (?, ?,
?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "parth";
$lastname = "gandhi";
$email = "gandhi#example.com";
$stmt->execute();
?>
here in bind_param method in first parameter s is stands for string. if you want to use integer there you can use "i" and for decimal "d".
thanks for reading my solution.
I'm getting this error for the following php code on line 12. I'm trying to insert data into a table and if it succeeds, redirect to another page after alert.
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO '.$depname.'(name,hof,tier,services,method,address,phone) VALUES ('$name','$hof','$tier','$services','$proced','$addr','$phone')"; //This is where the problem is;
if(mysqli_query($conn,$qry) === TRUE) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}
?>
In addition to what everyone else said this should fix your errors. You will still have security problems that you need to fix.
Also, I don't use mysqli I use PDO so you will have to forgive me if the syntax is slightly wrong.
Your problem is that mysqli_query() doesn't return a row. You need to need to fetch a row from your result and then assign it to $_SESSION['depname']
Login.php should look like this
// Note we are using prepared statements to prevent SQL injections
// Also note the use of backticks `, which are used for identifiers
$mysqli = new mysqli('host', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT `id`,`depname` FROM `admin` WHERE `username` = ? and password = ?');
$stmt->bind_param('ss', $myusername, $mypassword);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1) {
session_start();
$row = $result->fetch_assoc();
$_SESSION['depname'] = $row['depname'];
header("location: welcome.php");
exit;
}
Other Script
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO `{$depname}` (`name`,`hof`,`tier`,`services`,`method`,`address`,`phone`) VALUES (?,?,?,?,?,?,?)";
// prepare our query to prevent sql injections
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('sssssss', $name, $hof, $tier, $services, $proced, $addr, $phone);
$stmt->execute();
// not sure why you aren't using header here like #JayBlanchard said, but whatever
if($stmt->affected_rows == 1) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else
{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}
I have a customer login which the customer logins with email and application code. When the customer logins correctly it goes to PROFILE.PHP. In that profile I need to fetch and echo the details of the that customer only.
I have tried this what's wrong in this.
PROFILE.PHP
<?php
include("session.php");
$email = $_POST['email'];
$code = $_POST['code'];
$sql = mysql_query("SELECT firstname, lastname, mobileno FROM `loanapp` WHERE code = '$code' AND email = '$email'");
while ($row = mysql_fetch_array($sql)) {
echo $row['firstname'].'<br>';
echo $row['lastname'].'<br>';
echo $row['mobileno'].'<br>';
}
?>
SESSION.PHP
<?php
include('config.php');
session_start();
$check=$_SESSION['login_code'];
$session=mysql_query("SELECT code FROM `loanapp` WHERE code='$check' ");
$row=mysql_fetch_array($session);
$login_session=$row['code'];
if(!isset($login_session))
{
header("Location:../index.php");
}
?>
When the customer login correctly, need to echo all the details of that customer.
I agree with ByteHamster,
Your code is vulnerable to SQL Injection -> http://www.w3schools.com/sql/sql_injection.asp
Always use the prepare statement.
Here's a quick code for login:
try {
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users WHERE userID = :usr AND userPass = :pas;");
$stmt->bindParam(':usr', $user);
$stmt->bindParam(':pas', $pass);
$stmt->execute();
if($stmt->rowCount() > 0){
echo "User Exists"; // You can retrieve the user data now
} else {
echo "non existant"; // wrong username or password
}
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
profile.php
<?php
session_start()
include("session.php");
$email = $_POST['email'];
$code = $_POST['code'];
$sql = mysql_query("SELECT firstname, lastname, mobileno FROM `loanapp` WHERE code = '$code' AND email = '$email'");
while ($row = mysql_fetch_array($sql)) {
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['mobileno'] = $row['mobileno'];
}
?>
Then you can use them whenerver you want
For example,
<div><?php echo $_SESSION['firstname'];?></div>
First of all I would suggest you to not start the session like session_start() in the profile.php as you're already including session.php in the page and have already started session in the session.php.
Also I would suggest to use the function at the start of the page even above including config.php or you can use the session function in config.php as well.
Here is the pretty simple code with explanation.
<?php
// Defining variables of values
$email = $_POST['email'];
$code = $_POST['code'];
// Select the data using mysql query
$sql = mysql_query("SELECT * FROM `loanapp` WHERE code = '$code' AND email = '$email'");
// Looping to get all the data into session
while ($row = mysql_fetch_assoc($sql)) {
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['mobileno'] = $row['mobileno'];
}
?>
What I made changes in the code is:
Removed session_start() in profile.php as per my above suggestion
used * in query in case you need more details from the table in
future so all you need to add the key with $row. But using * is
suggested if your table has limited fields
Used mysql_fetch_assoc() for associative array so you can get array
with key named field name, not any extra numeric keys
Note: If you're specifying fields in query then you can easily create
all the session with field name using foreach loop.
I hope it'll help you to understand conceptual points as well.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I have the following code in my php file:
session_start();
include "connect.php";
if (isset($_POST['email']) && isset($_POST['password'])) {
$email = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['email']));
$password = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['password']));
function process() {
include "connect.php";
if (isset($_POST['email']) && isset($_POST['password'])) {
$email = $_POST["email"];
$password = $_POST["password"];
}
mysqli_select_db($conn, "users");
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count >= 1) {
$_SESSION['id'] = $id;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header('location:index.php');
} else {
echo "Email/Password is incorrect";
}
}
if ($email != "" or $password != "") {
if (isset($_POST['submit'])) {
process();
} else {
echo "Error: " . mysql_error();
}
}
}
How would I go about preventing sql injection in my login page?
I searched on the internet and most sites said I must use the mysqli_real_escape_string() function, but this did not seem to change things at all when I used the sql injection in my site again.
please help :)
Yes, use PDO and prepare statements with try/catch blocks. When using prepare, each passes as a secure parameter, eliminating risk of injection.
Use sql prepare :)
http://www.php.net/manual/en/mysqli.prepare.php
From what I know this filters any sql injection
foreach($_POST as $key => $value) $_POST[$key] = mysqli_real_escape_string($value);
Most simple way, anyway i suggest of use prepare statements
First of all, - to avoid sql injection you need to filter any kind of user input. And simplest way to do it, is to use PDO
You need to use prepared statements. I think following code snippet will give you some idea how to use it. please change according to your requirements
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT * FROM users WHERE email=? AND password=?")) {
/* Bind parameters
s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $email, $password);
/* Execute it */
$stmt -> execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
header('location:index.php');
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
Docs Link: http://www.php.net/manual/en/mysqli.prepare.php
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/
im new at programing and php, and i want to create an error on my registration system that when the user creates an account with the same username already existing in the database it says something like this: "Username already in use" and then if it isnt an existing username it says "Registation Complete"
I tried this code:
<?
require ("conect.php");
$user = $_POST['user'];
$pass = $_POST['password'];
$email = $_POST['email'];
$email_check = $_POST['email_check'];
$register = mysql_fetch_array;
if($user = $register[user]) {
echo"Username already in use";
}
else
{
$insert = mysql_query("INSERT INTO registration (user, password, email)
VALUES('$_POST[user]','$_POST[password]','$_POST[email]')");
echo "The account $user was successfully created.";
}
?>
But it didnt work, can someone help please
As pointed out by the other users, you should be using prepared statements through PDO (or mysqli, but I definitely prefer PDO)
You're storing the POSTS in variables, but then in the database query you are just using the $_POST variable again?
I'm not sure what your doing with the $register = mysql_fetch_array part, but to get the desired functionality you should use a select query to count the number of users using the username.
You're not using any secure hash format to store the password. I switched it to use password_hash().
Try something like this (I haven't tested the code yet though, so there might be errors):
<?php
//Put all POSTS in variables
$user = $_POST['user'];
$pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
$email_check = $_POST['email_check'];
//Database config- probably should store in a separate file
$database_host = "";
$database_name = "";
$database_user = "";
$database_password = "";
$conn = new PDO("mysql:host=$database_host;dbname=$database_name",$database_user,$database_password);
//Find out if the username is taken.
$sql = "SELECT count(*) FROM `registration` WHERE user = :user";
$q = $conn->prepare($sql);
$q->execute(array(':user' => $user));
$number_of_rows = $q->fetchColumn();
//Clear $sql and $q so you can use them again
$sql = NULL;
$q = NULL;
if ($number_of_rows > 1) {
//Username already taken
echo "Username already taken";
}
else {
$sql = "INSERT INTO registration (user,password,email) VALUES (:user,:password,:email)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$user, ':password'=>$password, ':email'=>$email));
echo "The account " . $user . " was successfully created";
}
?>
You really, really need to read about prepared statements. The method you are using is very old, incredibly insecure, and generally a bad-practice by today's standards.
Your code isn't even worth fixing for these reasons, it should be re-written using prepared statements.