Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am trying to insert data into MySQL tables but I am not sure why it is not working
<?php
include 'connect.php';
$userName = $_POST['name'];
$firstname = $_POST['FirstName'];
$Surname = $_Post['Surname'];
$email = $_POST['EmailAddress'];
$password = $_POST['Password'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`)
VALUES ('.$userName.','.$password.','.$firstname.','.$Surname.', '.$gender.', '.$dob.', '.$email.')';
$stmt = $conn->prepare($query);
try {
$myarray = array(
":userName" => $userName,
":password" => $password,
":firstname" =>$firstname,
":Surname" => $Surname,
":gender" => $gender,
":dob" => $dob,
":email" => $email);
print_r($myarray);
$stmt->execute($myarray);
} catch(PDOException $err) {
echo "Houston we have a problem: $err";
}
?>
Please tell me if I am doing something wrong.
You're using Prepared Statements wrong. With $db->prepare() you're actually submitting the query with placeholders and not with the values (called sending a template). In your case:
$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`)
VALUES (:userName, :password, :firstname, :Surname, :gender, :dob, :email)';
First make sure you have connected to the sql properly then change your codes to this one:
$table='User';
$sql="INSERT INTO
$table(username,Password,First Name,Surname,Gender,DOB,Email Address) VALUES ('$userName','$password','$firstname','$Surname', '$gender', '$dob', '$email')";
$result=$conn->query($sql) ;
Good Luck!
use this one for connection :
$db = "mysql:host=yourhost;dbname=yourdbname";
$username = " ";
$password = " ";
$conn = new PDO( $db, $username, $password ) or die("Error Connection !! ");
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
Try this approach:
<?php
include 'connect.php';
$userName = $_POST['name'];
$firstname = $_POST['FirstName'];
$Surname = $_Post['Surname'];
$email = $_POST['EmailAddress'];
$password = $_POST['Password'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`)
VALUES (:userName, :password, :firstname, :Surname, :gender, :dob, :email)'
try {
$stmt = $conn->prepare($query);
$result = $stmt->execute(array(
":userName" => $userName,
":password" => $password,
":firstname" =>$firstname,
":Surname" => $Surname,
":gender" => $gender,
":dob" => $dob,
":email" => $email));
if ($result) {
// success!
echo 'lastInsertId = '.$conn->lastInsertId();
} else {
// Query failed.
echo 'errorcode = '.$stmt ->errorCode();
}
} catch(PDOException $err) {
echo "Houston we have a problem: $err <br />";
echo 'errorcode = '.$stmt ->errorCode();
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
<?php
error_reporting(E_ALL);
$username = $_POST['username'];
$email_id = $_POST['email_id'];
$phone_no = $_POST['phone_no'];
$gender = $_POST['gender'];
$country = $_POST['country'];
$courses = $_POST['courses'];
//i am checking here values***
if (!empty($username) || !empty($email_id) || !empty($phone_no) || !empty($gender) || !empty($country) || !empty($courses)) {
//db connectiion***
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "registartionform";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
//check email already exists or not and insert the value in db***
$SELECT = "SELECT email_id From registration Where email_id = ? Limit 1";
$INSERT = "INSERT Into registration (username, email_id, phone_no, gender, country, courses) values($username, $email_id, $phone_no, $gender, $country, $courses)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
if ($stmt !== false) {
$stmt->bind_param("s", $email_id);
$stmt->execute();
$stmt->bind_result($email_id);
$stmt->store_result();
$rnum = $stmt->num_rows;
}
if ($rnum == 0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ss", $username, $email_id, $phone_no, $gender, $country, $courses);
if ($stmt !== false) {
$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();
}
You can't do this
INSERT Into registration (username, email_id, phone_no, gender, country, courses)
values($username, $email_id, $phone_no, $gender, $country, $courses)
and then try to bind variables
$stmt->bind_param("ss", $username, $email_id, $phone_no, $gender, $country, $courses );
You should use placeholders in your SQL query. Try with:
INSERT Into registration (username, email_id, phone_no, gender, country, courses)
values(?, ?, ?, ?, ?, ?)
Values will be provided in bind_param variables.
Also you have 7 variables in bind_param and only 6 columns in your INSERT statement. You need to mach that or SQL wont know where to put data.
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I'm getting these warnings from web host which contains my database. I'm trying to get an Android app developed in Android Studio to send data from a Register user activity to a database. I think I'm having a PHP Script error.
Below is my PHP code for registering user:
<?php
$con = mysqli_connect("localhost", "user", "pass", "db");
if (isset($_POST["name"], $_POST["email"], $_POST["username"], $_POST["password"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
}
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, email, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $username, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
You have check for errors:-
<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);
$con = mysqli_connect("localhost", "id2833909_split421", "pass123", "id2833909_splitw");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST["name"], $_POST["email"], $_POST["username"], $_POST["password"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO `user` (`name`, `username`, `email`, `password`) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $name, $username, $email, $password); // i need to be s
$response = array();
if(mysqli_stmt_execute($statement)){
$response["message"] = "success";
}else{
$response["message"] = "error";
}
echo json_encode($response);
}
?>
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.
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.
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);