The issue I am having is the PHP code below only inserts the data into one table blue. What I want is if the directory category from the POST is equal to for example blue INSERT into Table blue , but if it is equal to yellow INSERT into yellow, but if it's equal to red INSERT into table red.
The only answers I have found deal with insert if exist but not multiple insert if statements. Any help would be greatly appreciated. I am just learning PHP code.
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some directory','password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Connection failed : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$firstname = '$_POST[firstname]';
$lastname = '$_POST[lastname]';
$city = '$_POST[city]';
$state = '$_POST[state]';
$zipcode = '$_POST[zipcode]';
$directorycategory = '$_POST[directorycategory]';
$active = '$_POST[active]';
$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
$statement = $mysqli->prepare($query);
//bind parameters
$statement->bind_param('sssssss', $_POST['firstname'], $_POST['lastname'], $_POST['city'], $_POST['state'], $_POST['zipcode'], $_POST['directorycategory'], $_POST['active']);
if($statement->execute()){
header("some location");
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
#oremIpsum1771 Your answer works the best. The final code is as follows
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some directory','password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Connection failed : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$firstname = '$_POST[firstname]';
$lastname = '$_POST[lastname]';
$city = '$_POST[city]';
$state = '$_POST[state]';
$zipcode = '$_POST[zipcode]';
$directorycategory = '$_POST[directorycategory]';
$active = '$_POST[active]';
if($directorycategory == 'Employer'){
$query = ("INSERT INTO employer(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
}
else if($directorycategory == 'Blue'){$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Green'){$query = ("INSERT INTO green(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Red'){$query = ("INSERT INTO red(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Orange'){$query = ("INSERT INTO orange(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
$statement = $mysqli->prepare($query);
//bind parameters
$statement->bind_param('sssssss', $firstname, $lastname, $city, $state, $zipcode, $directorycategory, $active);
if($statement->execute()){
header("some location");
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
I'm not seeing where you have the control structure for the query. If i'm understanding the problem correctly, I would think that you would need something like this:
if(directorycategory == 'blue'){$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if(directorycategory == 'yellow'){$query = ("INSERT INTO yellow(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
etc....
$query = ("INSERT INTO ".$_POST['directorycategory']."(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
http://php.net/manual/en/language.operators.string.php
You can use the period to concatenate strings with variables to make 1 big string.
Related
new here
I've come across this problem.
It doesn't seem to be able to use my id's from the two first statements in my last statements as a variable resource, so the sqlcharacter statement fails.
What do i do wrong?
$sqlimg = ("INSERT INTO cimages(image) VALUES(?)");
$stmtimg = $conn->prepare($sqlimg);
$stmtimg->bind_param('s', $image);
$stmtimg->execute();
$img_id = $stmtimg->insert_id;
// I insert the picture first, and retrieve it's ID
$sqlstats = ("INSERT INTO cstats(Strength, Dexterity, Constitution,
Intelligence, Wisdom, Charisma, Aligment) VALUES(?, ?, ?, ?, ?, ?, ?)");
$stmtstats = $conn->prepare($sqlstats);
$stmtstats->bind_param("iiiiiis", $strength, $dexterity, $constitution,
$intelligence, $wisdom, $charisma, $aligment);
$stmtstats->execute();
$stats_id = $stmtstats->insert_id;
// I insert the characters stats, and retrieve it's ID
// Last I insert The user_id and img_id and stats_id
$user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
// I've used the session id to get the user_id already
$sqlcharacter = ("INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
$img_id, $stats_id)");
$stmtChar = $conn->prepare($sqlcharacter);
$stmtChar->bind_param('ssssssiii', $Cname, $Clast, $Crace, $house,
$location, $Bgstory, $user_id, $img_id, $stats_id);
$stmtChar->execute();
The $sqlcharacter string looks like you've got two variables $img_id and $stats_id in there instead of ?, so I think that's why it's not binding those values.
Try changing this:
"INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
$img_id, $stats_id)"
To this:
"INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
?, ?)"
I recieve the echo before the bind_param statment but not after it
$stmt = $this->conn->prepare("INSERT INTO restaurants(unique_id, name, type, longitude, latitude, value_for_money, cleanliness, view, atmosphere, staff created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
echo "ezzat wasal";
$stmt->bind_param("sssddiiiii", $uuid, $name, $type, (double)$longitude, (double)$latitude, (int)$value_for_money, (int)$cleanliness, (int)$view, (int)$atmosphere, (int)$staff);
echo "ana zeh2et";
You are missing a comma between staff and created_at. Also I would suggest quoting all column names in the query (because some of them are reserved words in mySQL: name, type, view):
$stmt = $this->conn->prepare("INSERT INTO `restaurants`
(`unique_id`, `name`, `type`, `longitude`, `latitude`, `value_for_money`,
`cleanliness`, `view`, `atmosphere`, `staff`, `created_at`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
I'm new to using mysqli_stmt statements in PHP. No matter, what I try, I can't insert data into my table. I have 2 tables, one, I can insert the data in but this one does not work
if ($new_profile_query = mysqli_prepare($db,
"INSERT INTO profile (
uid,
first_name,
last_name,
biography,
interests,
date_of_birth) VALUES (
?,
?,
?,
?,
?,
?)")) {
//VALUES ('$user_numberr', '$fname', '$lname', '$biography', '$interests', '$dob')";
mysqli_stmt_bind_param($new_profile_query,
"issbbs",
$user_numberr,
$fname,
$lname,
$biography,
$interests,
$dob);
mysqli_stmt_execute($new_profile_query);
mysqli_stmt_close($new_profile_query);
}
I make code that using pdo to insert information to database and gain XSS protection.
now im few days look at the code and dont see the problem that make the code to not insert the requird information.
Here`s My code:
if ($register = $mysqli->prepare("INSERT INTO `accounts`(`id`, `username`, `email`, `password`, `salt`, `fullname`, `birthdate`, `gender`, `secure question`, `secure answer`, `asked`, `answered`, `lastlogin`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
$register->bind_param("ssssssddsdds", $username, $email, $password, $random_salt, $fullname, $birthdate, $gender, $question, $answer, $z, $z, $lastlogin);
// Execute the prepared query.
if (! $register->execute()) {
echo "אירעה שגיאה";
$register->close();
}else{
echo 'אתם נרשמתם בהצלחה!. לחצו כאן';}
$register->close();
}
And the connection code:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
Thank you.
Use mysqli_affected_rows to get the number of inserted row, if any function fails, check for errors using mysqli_error
$sql = "INSERT INTO `accounts`(`id`, `username`, `email`, `password`, `salt`, `fullname`, `birthdate`, `gender`, `secure question`, `secure answer`, `asked`, `answered`, `lastlogin`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($register = $mysqli->prepare($sql)) {
$register->bind_param("ssssssddsdds", $username, $email, $password, $random_salt, $fullname, $birthdate, $gender, $question, $answer, $z, $z, $lastlogin);
// Execute the prepared query.
if (!$register->execute()) {
echo "אירעה שגיאה";
die("execute() failed: ". mysqli_error($mysqli));
}
if(mysqli_affected_rows($register) > 0){
echo 'אתם נרשמתם בהצלחה!. לחצו כאן';
}else{
echo 'Did not inser any row';
}
}else{
die("prepare() failed: ". mysqli_error($mysqli));
}
I was always using normal querys for inserting data into the database but now I want to make it with prepared statements. I'm already using statements to select data in all my files but insert never worked... And now I ran out of ideas again. Maybe someone can see what I did wrong.
$animeId = $_POST['animeId'];
$username = $_POST['username'];
$rating = $_POST['rating'];
$story = $_POST['story'];
$genre = $_POST['genre'];
$animation = $_POST['animation'];
$characters = $_POST['characters'];
$music = $_POST['music'];
//Datum auslesen
$date = date("Y-m-d H:i:s");
if($insertRating = $con->prepare("INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?"))
{
$insertRating->bind_param("iiiiiiiss", $animeId, $rating, $story, $genre, $animation, $characters, $music, $username, $date);
$insertRating->execute();
$insertRating->close();
}
You have an errant comma in your query:
music, user,) VALUES (?, ?, ?, ?, ?, ?, ?
^^^
HERE
It should be
music, user) VALUES (?, ?, ?, ?, ?, ?, ?
In the statement:
INSERT INTO anime_rating (
animeId,
rating,
story,
genre,
animation,
characters,
music,
user /* 8 columns */)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?") /* 10 parameters */
There are 8 columns listed to insert values into and 10 parameters specified in the values section. Also as pointed out there is the extra comma in the list of values.
The number of columns must match the number of parameters and the number of parameters binding in the following statement:
`$insertRating->bind_param("iiiiiiiss", $animeId, $rating, $story, $genre, $animation, $characters, $music, $username, $date);`
Two errors in the statement:
INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user,) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?"
^ here and ^ ^
remove the comma
add a closing parentheses before the end of the string.
remove one ,?
Furthermore you should chop one is from the binding:
$insertRating->bind_param("iiiiiiss", $animeId, $rating, $story, $genre, $animation, $characters, $music, $username, $date);
if($insertRating = $con->prepare("INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?"))
The last (") should be placed after the first ) at the end
New code:
if($insertRating = $con->prepare("INSERT INTO anime_rating (animeId, rating, story, genre, animation, characters, music, user, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")