<?php
require_once 'Connect.php';
//Prepare HTML insert statement binding parameters
$stmt = $conn->prepare("INSERT INTO records (`Title`, `FirstName`, `LastName`, `Gender`, `DOB`, `Mem.Expiry`, `Mem.Type`, `EmailAddress`)
VALUES (:Title, :Fname, :Lname, :Gender, :DOB, :MemX, :MemType, :Email)");
$title = $_POST['Title'];
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$memx = $_POST['MemX'];
$memtype = $_POST['MemType'];
$email = $_POST['Email'];
//Attempt row insertion by executing prepared statement
try
{
//Insert a row
$stmt ->bindParam(':Title', $title);
$stmt ->bindParam(':Fname', $fname);
$stmt ->bindParam(':Lname', $lname);
$stmt ->bindParam(':Gender', $gender);
$stmt ->bindParam(':DOB', $dob);
$stmt ->bindParam(':MemX', $memx);
$stmt ->bindParam(':MemType', $memtype);
$stmt ->bindParam(':Email', $email);
$stmt->execute();
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
I have a web form that updates a database connected to localhost. I would like to implement a primary key. When I include the ID column and set it to primary key, how can I implement that it auto fills in the code above? I have looked online, but I couldn't find anything helpful.
I cleared the database and inserted a primary key. Now when I fill out the form the first input will be uploaded and the primary key will be 0. After this no other information is being registered?
I think you are looking for Auto Increment
Related
I am trying to figure out how prepared statements work in PDO. I have the following file:
<?php
$user = "root";
$pass = "<removed for this post>";
$db = new PDO("mysql:host=localhost;dbname=pdo-demo", $user, $pass);
$stmt = $db->prepare("INSERT INTO pdo-demo (firstname, lastname, email) value (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$firstname = "John";
$lastname = "Doe";
$email = "johndoe#nowhere123.com";
$stmt->execute();
$db = null;?>
When I enter the page nothing happens, what am I missing? Shouldn't it insert the data?
pdo-demo that translates to pdo minus demo And your using that name for database AND table.
Turns out I needed backticks (`) for the variable names like so:
$stmt = $db->prepare("INSERT INTO `pdo-demo` (`firstname`, `lastname`, `email`) value (:firstname, :lastname, :email)");
Now it worked
// Do not put any echo code other than the last line.
// didnt include $con in the post.
$userlvlid = $_POST["userlvlid"];
$username = $_POST["username"];
$password = $_POST["password"];
$lname = $_POST["lname"];
$fname = $_POST["fname"];
$mname = $_POST["mname"];
$birthdate = $_POST["birthdate"];
$streename = $_POST["streetname"];
$province = $_POST["province"];
$city = $_POST["city"];
$barangay = $_POST["barangay"];
$organization_name = $_POST["orgname"];
$email_address = $_POST["email_address"];
$license = $_POST["license"];
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
else{
// means connection successful.
echo "sucess";
}
$response = array();
$response["success"] = false;
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// means username already exists.
}
else {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO accounts (`userlvlid`,
`username`,
`password`,
`lname`,
`fname`,
`mname`,
`birthdate`,
`streetname`,
`region`,
`province`,
`city`,
`barangay`,
`orgname`,
`email`,
`license`)
VALUES
('$userlvlid',
'$username',
'$password',
'$lname',
'$fname',
'$mname',
'$birthdate'
'$streetname',
'$region',
'$province',
'$city',
'$barangay',
'$organization_name',
'$email_address',
'$license')";
if (mysqli_query($con, $sql)) {
$response["success"] = true;
}
else {
}
}
}
echo json_encode($response);
?>
Can someone explain why "mysqli_query($con, $sql)" is returning false? I can't find what is wrong in the code. my database contains all of the fields and here maybe a syntax error. The code doesn't give me any errors and it doesn't add the information to the database.
A few things, first this part is not needed:
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// means username already exists.
}
Why? Because in between the time that you check for the user's existence and the time that you insert a new record, another client may create a user with the same username. So your second query the insert will fail if it happens (provided of course that you have a unique index on your username as you should).
Secondly, you are not escaping parameters. This leaves you open to SQL injection attacks. And it could also lead to malformed queries that do not get executed correctly - result data is not inserted. Use prepared statements instead.
$sql = mysqli_prepare($con,"INSERT INTO accounts (`userlvlid`,
`username`,
`password`,
`lname`,
`fname`,
`mname`,
`birthdate`,
`streetname`,
`region`,
`province`,
`city`,
`barangay`,
`orgname`,
`email`,
`license`)
VALUES
(?,?,?,?,?,?,?,?,?...)";
Then you need to bind the params
mysqli_bind_params($stmt,('$userlvlid',"ssssssssssssss",
$userlvlid
$username,
$password,
$lname,
$fname,
$mname,
$birthdate,
$streetname,
$region,
$province,
$city,
$barangay,
$organization_name,
$email_address,
$license));
Ugly isn't it? That's why one should use PDO instead of mysqli but using mysqli without prepared statements is just horrible so we have to slog through this.
Now while going through this copy paste, I discovered the real cause of your problem
'$mname',
'$birthdate' /*** no comma here ***/
'$streetname',
Try using echo for the $sql and place the exit after that statement. So that it breaks the query execution after that.
By doing this you can find whether any error is available in the query and you can rectify it.
Note: You first put echo to the Insert Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;
If you have any Table Column mismatch or and Data Discrepancy you can rectify with the help of this echoed query.
Ensure that you provide values that are matching the values that are given into the DB.
**Note: **(E.g) if userlvlid - varchar(11) - You should provide value which is equal to 11 or less than 11 if you enter the value greater than 11 it will not be inserting and the query will fail from there on.
I have a weird error, using MyPhpAdmin, I added a row, and the script it generates is:
INSERT INTO 'Users'.'User_Accounts'('Account_ID', 'UserName',
'Email', 'PhoneNumber', 'Password') VALUES (NULL, 'fdsfsadf',
'dfsadf', 'sdfads', 'fsdfasdfsd');
That works, however when I use PHP PDO to insert it gives this error:
Table 'Users.User_Acounts' doesn't exist
uhhhh yes it does...
The PHP code:
$hostname = "127.0.0.1";
$port = "3306";
$database = "Users";
$username = "AccountControl";
$password = "w67hLAanWESGNJMC";
echo ">>";
$db = new PDO("mysql:host=$hostname; port=$port; dbname=$database", $username, $password);
echo ">>";
$UserName = "KiteDev";
$Email = "johndoveail.com";
$PhoneNumber = "66666";
$Password = "dfsgetagfdasg";
// Create the query
$query = "INSERT INTO User_Acounts (UserName, Email, Phon2eNumber, Password) VALUES (:name, :email, :phone, :pass )";
// Prepare statement with $stmt variable
$stmt = $db->prepare($query);
echo ">>";
// Bind parameters, (you can also remove the PDO::PARAM_INT)
$stmt->bindParam(':name', $UserName, PDO::PARAM_STR);
$stmt->bindParam(':email', $Email, PDO::PARAM_STR);
$stmt->bindParam(':phone', $PhoneNumber, PDO::PARAM_STR);
$stmt->bindParam(':pass', $Password, PDO::PARAM_STR);
// Execute the query once you're done binding all the params
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
echo ">>";
Any ideas as to what's causing this?
You've misspelled User_Accounts. The table you created is User.User_Accounts but the table that doesn't exist is User.User_Acounts.
You wrote accounts with one c
Table 'Users.User_Acounts' doesn't exist
The Table Name is User_Accounts. In your php code, it is misspelled as User_Acounts
Correct it as
$query = "INSERT INTO User_Accounts (UserName, Email, Phon2eNumber,
Password) VALUES (:name, :email, :phone, :pass )";
i am getting this error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO student_details (student_id, first_name, last_name, dob, address_lin' at line 2
for this code: any idea?
//create variables from each value that was submitted from the form */
$student_info_id = $_POST['student_info_id'];
$class_id = $_POST['class_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$dob = $_POST['dob'];
$address_line_1 = $_POST['address_line_1'];
$address_line_2 = $_POST['address_line_2'];
$town = $_POST['town'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
$gender = $_POST['gender'];
$ethnicity = $_POST['ethnicity'];
try {
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $password);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "
INSERT INTO student_info (student_info_id, class_id) VALUES (:student_info_id, :class_id)
INSERT INTO student_details (student_id, first_name, last_name, dob, address_line_1, address_line_2, town, county, postcode, gender, ethnicity, student_info_id)
VALUES (:student_id, :first_name, :last_name, :dob, :address_line_1, :address_line_2, :town, :county, :postcode, :gender, :ethnicity, :student_info_id)
";
$statement = $conn->prepare($sql);
$statement->bindValue(":student_info_id", $student_info_id);
$statement->bindValue(":class_id", $class_id);
$statement->bindValue(":student_id", $student_id);
$statement->bindValue(":first_name", $first_name);
$statement->bindValue(":last_name", $last_name);
$statement->bindValue(":dob", $dob);
$statement->bindValue(":address_line_1", $address_line_2);
$statement->bindValue(":address_line_2", $address_line_1);
$statement->bindValue(":town", $town);
$statement->bindValue(":county", $county);
$statement->bindValue(":postcode", $postcode);
$statement->bindValue(":gender", $gender);
$statement->bindValue(":ethnicity", $ethnicity);
$statement->bindValue(":student_info_id", $student_info_id);
$count = $statement->execute();
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
I'm not sure if PDO support multiple statements, but if so, the error is that you did not terminate the first statement,
INSERT INTO student_info (student_info_id, class_id)
VALUES (:student_info_id, :class_id);
^ add this one
You'll have to finish the first INSERT with a ; Like this:
INSERT INTO student_info (
student_info_id,
class_id
) VALUES (
:student_info_id,
:class_id
); <-- a semicolon is the default statement separator, use it
....
Note that, although it is possible to run multiple queries at once, I would not advice you to do it. If you would run each query one by one you would have a better control over errors.
You can't run multiple queries in one call.
Run them separately, one by one.
After migrating to PDO from a previous question, I've hit a small snag. I can't insert information into a MySQL table.
Here's what I have:
include_once(db.php);
$platform = $_POST['platform'];
$location = $_POST['location'];
$name = $_POST['name'];
$secret = sha1($_POST['password']);
$sql = $db->prepare("INSERT INTO `servers` (`id`, `secret`, `platform`, `location`, `name`) VALUES (:id, :secret, :platform, :location, :name)");
$sql->bindValue(':id', 'null');
$sql->bindValue(':secret', $secret);
$sql->bindValue(':platform', $platform);
$sql->bindValue(':location', $location);
$sql->bindValue(':name', $name);
$sql->execute();
I can't find a reason why it won't insert new records.
I durr'd hard.
include_once(db.php); needed quotes: include_once("db.php");
I feel like a gigantic moron for wasting 2 hours on why inserting wouldn't work.