php mysqli transactions are not storing second query - php

ive been struggling with this for hours now. i have a 2 step registraton form and transfered all input to session variables and they all work on the second step. however, when i try to insert data to the second table nothing gets stored and i cannot figure out why.
<?php
include ("encrypt.php");
$conn = mysqli_connect($servername, $dbuser, $dbpassword, $dbname);
$problem = '';
$firstName = $_SESSION['firstName'] ;
$lastName = $_SESSION['lastName'];
$email = $_SESSION['email'];
$username= $_SESSION['username'];
$password= $_SESSION['password'];
$pass = encrypt($password);
if(isset($_POST["mysubmit"]) && ($_POST["mysubmit"]=="Submit Form")){
$dOb = mysqli_real_escape_string ($conn, $_POST["eventDate"]);
$difficulty = mysqli_real_escape_string ($conn, $_POST ["difficultyCatagory"]);
$club = mysqli_real_escape_string ($conn,$_POST["clubSelect"]);
echo $dOb, $difficulty, $club, $firstName, $lastName, $email, $username,$password, $pass;
mysqli_autocommit($conn,FALSE);
mysqli_query($conn,"INSERT INTO userBMX (username,password) VALUES ('$username', '$pass')");
mysqli_query($conn,"INSERT INTO userDetailsBMX(userID, firstName, lastName, email, dateofBirth, Status, club)
VALUES (last_insert_id(),'$firstName','$lastName','$email','$dOb','$difficulty','$club')");
mysqli_commit($conn);
echo 'stored';
/*header ("Location: login.php");*/
}
else{
echo "ERROR: was not able to execute $conn. " . mysqli_error($conn);
}
?>

Related

HTML form returns PHP script instead of success message

There is an html form which I want to store data from in a database. After filling the form, it returns the php script instead of success message. And no data is getting stored in the database. Can you please help?
<?php
if (isset(['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$email = $_POST['email'];
}
if (!empty($username) || !empty($password) || !empty($gender) || !empty($email) {
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "cakeshop";
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_error().)')'. mysqli_connect_error());
}else {
$SELECT = "SELECT email From register Where email = ? Limit 1"
$INSERT = "INSERT INTO register (username, password, gender, email) values(?, ?, ?, ?)";
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0){
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssss", $username, $password, $gender, $email);
$stmt->execute();
echo "New record inserted successfully"
}else {
echo "Someone already registered";
}
$stmt->close();
$conn->close();
}
}
?>

php not adding data to database by using file.php?data=value

I have a form that I want to submit it without reloading the page with jquery. I am trying to make a form that will send the data to MySQL database with PHP.
This is the code in submit button onclick:
e.preventDefault();
var data = JSON.stringify($("form").serialize());
$.post("insert.php?" + data);
and this is the PHP file :
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$phoneCode = $_POST['phoneCode'];
$phone = $_POST['phone'];
if (!empty($username) || !empty($password) || !empty($gender) || !empty($email) || !empty($phoneCode) || !empty($phone)) {
$host = "localhost";
$dbUsername = "use";
$dbPassword = "user_pass";
$dbname = "test";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT email From register Where email = ? Limit 1";
$INSERT = "INSERT Into register (username, password, gender, email, phoneCode, phone) values(?, ?, ?, ?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssssii", $username, $password, $gender, $email, $phoneCode, $phone);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>
But it's not adding data to the database. I tried also writing the URL then the data like this: insert.php?data=value.But it didn't work. I am new to server-side and PHP, so I appreciate any help

How to query variable from database using php

Good Day developers outthere! 😊😊
I just wanna ask what is the problem with my code, I'm trying to make a webpage using html,css,php and database. Now I already created a php in my html form and my database is already connected, but everytime I submit the information in the html form I created, nothing appeared in my database.
<?php
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
echo "Successfully Added";
$sql= "INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, `Middle_Name') VALUES ('000',$FName,$MName)";
} else{
echo "<p>Insertion Failed.</p>";
}
?>
Just as #executable mentioned, you are defining query in your code but not executing it.
Define Connection Object (Mysqli, PDO..)
Prepare Query and Bind Variables
Execute your query
Here's an example using prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset($_POST['save']) ){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, Middle_Name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $transaction_number, $FName, $MName);
// set parameters and execute
$transaction_number = '000';
$FName= $_POST['FName'];
$MName= $_POST['MName'];
$stmt->execute();
echo "Successfully Added";
}else{
echo "<p>Nothing Posted</p>";
}
W3Schools and PHP.Net both have pretty good examples about how to use prepared statements to make your SQL Query more secure from SQL Injections.
You simply don't execute your query. Using MySQLi :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "dbthesis";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000', '$FName', '$MName')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Added";
} else {
echo "<p>Insertion Failed.</p>";
}
}
$conn->close();
You only making a query, not running query. This this code
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudioinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000','$FName','$MName')";
// code below runs your query
if (mysqli_query($conn, $sql)) {
echo "Successfully Added";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

MySQL error because of syntax in Custom PHP code

I am trying to enter user's data into a database. I think the commas in the address are causing the error.
<?php
$full_name = $_POST["fullname"];
$email = $_POST["email"];
$password = $_POST["password"];
$full_address = $_POST["address"];
$city = $_POST["city"];
$age = $_POST["age"];
$contact_number = $_POST["number"];
$gender = $_POST["gender"];
$education = $_POST["education"];
?>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
As others have noted, your code is vulnerable to SQL injections. You should consider using parameterized queries:
$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
For more information refer to the PHP manual on MySQLi prepared statements.
You need to quote string in your SQL statement;
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ('$full_name', '$email', '$password','$full_address','$city',$age,'$contact_number','$gender','$education')";
Notice the single quotes around all the variables that contain strings. I might be a bit off because I don't know the values or table structure.
But the just quote all values that are going in to a Date or Text field.
To avoid additional problems and security risks you should be using mysqli_real_escape_string (at a minimum).
In all your assignment statements wrap the values in mysqli_real_escape_string
$full_name = mysqli_real_escape_string($conn, $_POST["fullname"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
...
Note this requires setting up your DB connection before the variable assignments, so you'll have to reorganize your code a bit.
rink.attendant.6's answer is the proper way to adapt your code.

Data not entered into database from PHP

I am trying to enter data into a database with PHP.
Here is my code:
<?php
$username = 'username'; //username for database
$password = 'password'; //password for database
$hostname = 'localhost'; //host
$db_name = 'db_testdrubin'; //name of database
$db_selected = mysqli_connect($hostname, $username, $password, $db_name)//specify database
or die ("unable to connect");
if(isset ($_POST['submit'])){
$ID = ($_POST['ID']);
$fname = ($_POST['fname']);
$lname = ($_POST['lname']);
$address = ($_POST['address']);
$city = ($_POST['city']);
$state = ($_POST['state']);
$zip = ($_POST['zip']);
$phone = ($_POST['phone']);
$email = ($_POST['email']);
$books = ($_POST['books[]']);
$comments = ($_POST['comments']);
}
else{
echo'<p>not submitted</p>';
}
//up until this point the code works fine
$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';
$success = $db_selected->query($query);
if($success){
$count = $db_selected->affectd_rows;
echo '<p>$count were added</p>';
}
else{
echo '<p>error</p>';
}
?>
I know that the information is being read from the html form correctly because I have checked by printing the individual variables. I am not getting any error messages when I submit the form, just the "error" echo statement from the if/else statement, and no data is entered into the database.
I have also tried this:
if (!mysql_query($db_selected, $query)){
echo '<p>error</p>';
}
with the same results.
Change this
$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';
to
$query = "INSERT INTO Student VALUES ($ID, '$fname', '$lname', '$address', '$city', '$state', $zip, $phone, '$email', '$books', '$comments')";
I mean to say if its string then do like '$string' and also use
$db_selected->real_escape_string($stringval);
and use
echo $db_selected->error;
to check the error you got.
$ins="insert into Student (`id`,`fname`,`lname`,`address`,`city`,`state`,`zip`,`phone`,`email`,`books`,`comments`)values
('".$ID."','".$fname."','".$lname."','".$address."','".$city."','".$state."','".$zip."','".$phone."','".$email."','".$books."','".$comments."')";
mysql_query($ins);

Categories