Data not entered into database from PHP - 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);

Related

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

php mysqli transactions are not storing second query

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);
}
?>

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.

if(isset($_POST['submit'])){ } NOT WORKING on submit button

I have a problem where when ever I load my page it says that the form is done even when I don't press submit here is the code -
<?php
$db_host = 'localhost';
$db_name = 'info';enter code here
$db_user = 'root';
$db_password = '';
try {
$db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name, $db_user, $db_password);
echo "connected<br><br>";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
die();
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$info = $_POST['info'];
$date = $_POST['date'];
$sql = "INSERT INTO info (name, phone, email, info, date)";
$sql .= " VALUES (:name, :phone, :email, :info, :date)";
$query = $db->prepare($sql);
$query->execute(array(
':name' => $name,
':phone' => $phone,
':email' => $email,
':info' => $info,
':date' => $date
));
echo "done<br>";
}
?>
Add a check so it checks or something is posted:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//You code
}
I hope this will help.
Just use one && condition along with your isset
Lets just say, if this is your submit button
<input type="submit" value="SomeValue" name="SomeName">
Then you simply use this as your if condition to check if your button with name "SomeName" has actually been pressed.
if(isset($_POST['SomeName']) && $_POST['SomeName']=='SomeValue')
{
//Rest of your code
}
This If implies, your submit button has been pressed it after checking its value. Hope it helps.

Uncaught exception 'PDOException' error in my pdo

after running my code i got this kind of error, can anyone help me fix it please. The error starts after putting a code to filter if the email is duplicate or not in the database.
here is the error i got:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$email = #$_POST['email'];
$dupesql = "SELECT * FROM students WHERE email = :email ";
$dupesql = $dbc->prepare($dupesql);
$dupesql->bindParam(':name', $email);
$dupesql->execute();
$num_rows = $dupesql->rowCount();
if($num_rows === 0)
{
echo "1";
$q = "INSERT INTO students(name, age, address, gender, email ) VALUES(:name, :age, :address, :gender, :email)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':email', $email);
$results = $query->execute();
}else{
echo "0";
exit;
}
?>
Well you are facing this error because you are using a wrong parameter in your query.
$dupesql->bindParam(':name', $email);
:name doesn't exists so it should :email.

Categories