I have a big issue with my code I suspect.
It only adds the first of $species, $weight and $length. but if there is more than one value in the $_Post.
It should submit them as well from my form. I am having trouble seeing where I have gone wrong.
I hope somebody, can point me in the right direction?
<?php
require 'config.php';
$teamid = $_POST['teamid'];
$species = $_POST['species']; // Can be multiple values depending on how many lines added from form
$weight = $_POST['weight']; // Can be multiple values depending on how many lines added from form
$length = $_POST['length']; // Can be multiple values depending on how many lines added from form
// count($species),($weight),($length) - Should always be the same length
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Prepare an insert statement
$sql = "INSERT INTO indvejninger ( teamid, artid, vaegt, laengde) VALUES (?, ?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
foreach ($species as $key => $value) {
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssss", $_POST['teamid'], $param_species, $param_weight, $param_length);
$param_species = $species[$key];
$param_weight = $weight[$key];
$param_length = $length[$key];
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: index.php?limit=");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
I found the error, after first submit it changes url. So it does not finish the other submissions.
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: index.php?limit=");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
So instead, I need it to finish the other submissions, and then redirect to landing page.
Related
I'm developing a login/register form for my client. Right now I am working on the registration part of the form however I seem to have encountered an issue.
I am trying to append the user's input to a database if it does not currently exist. I'm developing this functionality using PHP version 7. However, the code does not seem to append the data to the database even when telling me it has done so successfully.
Here is code:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
//define variables and set values to null
$email = $code = "";
//set variable values to HTML input
$email = $_POST['email'];
$code = $_POST['code'];
//check if email exists
$stmt = $conn->prepare("SELECT userEmail FROM userDetails WHERE userEmail=?");
$stmt->bind_param("s", $prepemail);
//set parameters and execute
$prepemail = $email;
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "email exists";
return false;
} else {
//$stmt->close(); removed as per #Akintunde-Rotimi's suggestion
//insert email into database
$stmt = $conn->prepare("INSERT INTO userDetails (userEmail) VALUES (?)");
$stmt->bind_param("s", $newemail);
//set parameters and execute
$newemail = $email;
$stmt->execute();
echo "New records created successfully";
}
}
?>
The code successfully connects to the database and even tells me if the user already exists. It just doesn't add the user's email to the database and I can't seem to figure out why.
I have researched methods on how to insert the data into the database using prepared statements as I have done here. I've used W3Schools as a reference but still no luck.
The code doesn't seem to have any obvious spelling errors, so have you tried to catch errors? Replace
$stmt->execute();
with
if(!$stmt->execute()) {
trigger_error("there was an error....".$conn->error, E_USER_WARNING);
}
You can also check how many rows are affected, -1 meaning there was an error.
printf("%d Zeile eingefügt.\n", $stmt->affected_rows);
Also, enabling more errors to be shown (at least for development)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// ...
im developing shopping cart project , where everything works fine . i would like to ask i thing that how to insert all cart products in to database one by one
below is the code which i try but it only insert first session row not inserting all.
here is the code:
$User_Email=$_SESSION['User_Email'];
$date=date("d-m-Y");
foreach($_SESSION["shopping_cart"] as $v){
$sql = "INSERT INTO reservation (check_in,check_out,room_id,hotel_id,User_Email,date)
values
('{$v['Checkin']}','{$v['Checkout']}','{$v['room_id']}','{$v['room_id']}','$User_Email','$date')";
$update = mysqli_query($connection, $sql);
if ($update) {
$_SESSION['success'] = 'Information updated successfully';
header("location: my_account.php");
exit;
} else {
$_SESSION['errormsg'] = 'Someting is wrong in updating your Information, Please try again later.';
header("location: my_account.php");
exit;
}}
please tell me how to insert all cart values in to database.
thanks in advance.
You are using header() in your loop, this will redirect in first iteration either success of failure.
You can store success or failure status in an variable
if ($update) {
$status = 1;
} else {
$status = 0;
}
Then, move your condition outside your loop, as like:
if($status) // your success
{
header('your location');
exit;
}
else{ // failure
header('your location');
exit;
}
Make, sure $status declare as $status = 0; at top level declaration.
Note that, your code is wide open for SQL injection, for preventing SQL injection use PDO
Useful links:
How can I prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
I can't figure out why my redirection wont work?
All I get is a blank page with the same url from where I tried to redirect from..
The code is from my registration page, however I removed some code to make it easier to look at my redirection here. Everything else is working except the redirection.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
//removed bunch of code for clear overview for stackoverflow question
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
I think your redirect might work if you are going to this page.
Yo get a blank page because your code starts with:
if($_SERVER["REQUEST_METHOD"] == "POST"){
You state that you have removed some code. If the code you expect to run is also in that codeblock and it is no POST (this might be a GET), the code inside that codeblock will not be executed.
There is no form tag in your example, but you could also check if you use method="POST".
Hi I am working on simple crud project with php and mysqli statement.
First everything was working good, but for instance mysqli_num_rows($result) returns more than one row which cause all errors.
this is my PHP code
<?php
if(isset($_GET["email"]) && !empty(trim($_GET["email"]))){
// Include config file
require_once 'db.php';
// Prepare a select statement
$sql = "SELECT * FROM interns WHERE email = ?";
if($stmt = mysqli_prepare($con, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_GET["email"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$cin = $row["cin"];
$phone_number = $row["phone_number"];
$address = $row["address"];
$school = $row["school"];
$intern_duration = $row["intern_duration"];
$departement = $row["departement"];
$cv = $row["cv"];
$internship_report = $row["internship_report"];
} else{
// URL doesn't contain valid id parameter. Redirect to error page
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>
I know it's might be a very simple error but it driving me crazy xD
mysqli_stmt_bind_param($stmt, "i", $param_id) that should be an s for a string, being for the email address. The i stands for "integer".
Your query probably returns more than one row because there are (probably) more than one row containing an integer.
You could also add a LIMIT 1 to the query which may help.
I'm new to PHP and made a simple php site that allows me to submit a form and delete data stored in a database. I was told it was better to use prepared statements to avoid SQL Injection.
I updated my delete and it still works, not sure if it's totally right:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN ($getid)");
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
But I can't seem to get the add to database feature to work. I tried a variety of different ways to write it, but I'm sure that I'm missing something simple. Here's the unsafe code that I originally wrote:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
//execute query
if (mysqli_query($database,$assign)) {
header("Location:http://localhost/address-book/");
exit;
} else {
exit;
}
?>
If someone could guide me in the right direction I'd be thankful. I'm new to all of this.
UPDATED: I've updated my original code and came up with this instead for delete:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN (?)");
mysqli_stmt_bind_param($delete, 's', $getid);
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
and the add feature:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
$firstName = "$_POST[firstName]";
$lastName = "$_POST[lastName]";
$email = "$_POST[email]";
$phone = "$_POST[phone]";
// assigns form data to table columns
$assign = mysqli_prepare($database,"INSERT INTO contacts(firstName,lastName,email,phone) VALUES (?,?,?,?)");
mysqli_stmt_bind_param($assign, 'ssss', $firstName, $lastName, $email, $phone);
mysqli_stmt_execute($assign);
exit;
}
?>
A simple Prepare statement is something along the lines of
$query = $this->db->prepare("Query here WHERE something = ?") - note this example is taken from my site so you'll likely have something else instead of $this->->prepare.
The key thing is that the "= something " is denoted as a question mark.
You then bind the value of that question mark to the query
$query->bindValue(1, passed in parameter)
As a fully working example:
//function to add 1 to downloads each time a file is downloaded
public function addToDownload($filename){
$query = $this->db->prepare('UPDATE trainingMaterial SET downloads = downloads + 1 WHERE filename = ?');
$query->bindValue(1, $filename);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
Your query `$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
would be
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ?,?,?,?,?)";
$assign->bindValue(1, '$_POST[firstName]')
$assign->bindValue(2, '$_POST[lastName]')
etc etc