INSERT INTO not inserting for me - php

I can't see anything wrong with this, but it just wont work.
Quick rundown: Form filled in on previous page, $_POST['']'s added to $_SESSION['']'s, $vars set from the $_SESSION['']'s, $vars used to mysqli_query.
Im sure the problem is staring me in the face, but I just cant see it.
Heres the code: (UPDATED)
if(isset($_POST['list_make']) && $_POST['list_make'] != '') { $list_make = $_POST['list_make']; $_SESSION['list_make'] = $list_make; }
if(isset($_SESSION['list_make']) && $_SESSION['list_make'] != '') { $list_make = $_SESSION['list_make']; } else { $list_make = ''; }
$add_car_query = "INSERT INTO car_details
(car_user_id, car_user_number, car_date_added, car_make, car_model, car_date_registered, car_odometer,
car_engine_size, car_color, car_body_type, car_owners, car_nct_date, car_rax_date)
VALUES
('$user_id_new', '$new_user_number', '$today', '$list_make', '$list_model', '$list_year', '$list_kilometers',
'$list_engine_size', '$list_color', '$list_body_type', '$list_previous_owners', '$list_nct', '$list_tax')
";
if(mysqli_query($con, $add_car_query)) { $added = 'added'; } else { $added = 'Not happening'; }

Try checking if there is a MySQLi error in the else (which will be triggered if the query fails):
$add_car_query = "INSERT INTO car_details
(car_user_id, car_user_number, car_date_added, car_make, car_model, car_date_registered, car_odometer,
car_engine_size, car_color, car_body_type, car_owners, car_nct_date, car_rax_date)
VALUES
('$user_id_new', '$new_user_number', '$today', '$list_make', '$list_model', '$list_year', '$list_kilometers',
'$list_engine_size', '$list_color', '$list_body_type', '$list_previous_owners', '$list_nct', '$list_tax')
";
if(mysqli_query($con, $add_car_query)) {
$added = 'added';
}
else {
// check for the error here
if(mysqli_error()) {
echo mysqli_error();
}
$added = 'Not happening';
}
Prepared Statements
As someone in the comments said, you should use prepared statements for better security. This way you don't have to worry about escaping input (it looks like you aren't escaping the values right now which is very dangerous).
It can get a bit confusing with the question mark placeholders though (MySQLi doesn't support named parameters unfortunately). Prepared statements are nicer with OOP MySQLi, but you're using procedural so here's how you do a prepared statement for the query in your question:
$add_car_query = "INSERT INTO car_details
(car_user_id,
car_user_number,
car_date_added,
car_make,
car_model,
car_date_registered,
car_odometer,
car_engine_size,
car_color,
car_body_type,
car_owners,
car_nct_date,
car_rax_date)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_prepare($con, $add_car_query);
// if any of the values are an int, change the
// corresponding 's' (which means string) to 'i' (integer).
// more info: http://us.php.net/manual/en/mysqli-stmt.bind-param.php
mysqli_stmt_bind_param($stmt, 'sssssssssssss',
$user_id_new,
$new_user_number,
$today,
$list_make,
$list_model,
$list_year,
$list_kilometers,
$list_engine_size,
$list_color,
$list_body_type,
$list_previous_owners,
$list_nct,
$list_tax);
$stmt_exe = mysqli_stmt_execute($stmt);
if($stmt_exe) {
$added = 'added';
}
else {
if(mysqli_error()) {
echo mysqli_error();
}
$added = 'Not happening';
}

Related

PHP sql SELECT from database is working, but sql INSERT INTO database is not working even though success message is shown [duplicate]

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 3 years ago.
I'm trying something new and at the same time practicing PHP. I have checked all the previous posts on StackOverflow and couldn't find the solution. I'm trying to insert some data into the database using PHP and PhpMyAdmin. Now the problem I'm facing is that the data from the database can be displayed (SELECT FROM) if I enter the data manually. When I try to insert data into the database dynamically using PHP example:
$sql = "INSERT INTO apps (appName, appDescription, appLinkFacebook, appLinkInstagram, appLinkPlaystore, appLinkWeb,appGoogleGamesIcon, appFullImageNameBackground, appFullImageNameIcon) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
I get no errors and I also get a success message that is supposed to show after the INSERT command was finished. The images I'm trying to insert are also successfully created inside designated folders and their names are also displayed in the right way. I already checked all the input fields names from the form, all the links and spelling a just can't seem to find the problem. I also tried using INSERT command while using the database on localhost and on a remote server and still nothing. If anyone has an idea on what to do please tell. Thanks
Here is the full source code of my upload.php file.
<?php
if (isset($_POST['btnUpload'])) {
$newFileNameCardBackground = $_POST['imgNameCardBackground'];
if (empty($newFileNameCardBackground)) {
$newFileNameCardBackground = "card_background";
} else {
$newFileNameCardBackground = strtolower(str_replace(" ", "-", $newFileNameCardBackground));
}
$newFileNameCardIcon = $_POST['imgNameCardIcon'];
if (empty($newFileNameCardIcon)) {
$newFileNameCardIcon = "card_icon";
} else {
$newFileNameCardIcon = strtolower(str_replace(" ", "-", $newFileNameCardIcon));
}
$appName = $_POST['appName'];
$appDescription = $_POST['appDescription'];
$appLinkFacebook = $_POST['appLinkFacebook'];
$appLinkInstagram = $_POST['appLinkInstagram'];
$appLinkPlaystore = $_POST['appLinkPlaystore'];
$appLinkWeb = $_POST['appLinkWeb'];
$appGoogleGamesIcon = $_POST['appGoogleGamesIcon'];
$fileCardBackground = $_FILES['fileCardBackground'];
$fileNameCardBackground = $fileCardBackground["name"];
$fileTypeCardBackground = $fileCardBackground["type"];
$fileTempNameCardBackground = $fileCardBackground["tmp_name"];
$fileErrorCardBackground = $fileCardBackground["error"];
$fileSizeCardBackground = $fileCardBackground["size"];
$fileCardBackgroundExtension = explode(".", $fileNameCardBackground);
$fileCardBackgroundActualExtension = strtolower(end($fileCardBackgroundExtension));
$fileCardIcon = $_FILES['fileCardIcon'];
$fileNameCardIcon = $fileCardIcon["name"];
$fileTypeCardIcon = $fileCardIcon["type"];
$fileTempNameCardIcon = $fileCardIcon["tmp_name"];
$fileErrorCardIcon = $fileCardIcon["error"];
$fileSizeCardIcon = $fileCardIcon["size"];
$fileCardIconExtension = explode(".", $fileNameCardIcon);
$fileCardIconActualExtension = strtolower(end($fileCardIconExtension));
$allowed = array("jpeg", "jpg", "png", "JPEG", "JPG", "PNG");
if (in_array($fileCardBackgroundActualExtension, $allowed) && in_array($fileCardIconActualExtension, $allowed)) {
if ($fileErrorCardBackground === 0 && $fileErrorCardIcon === 0) {
$imageFullNameCardBackground = $newFileNameCardBackground . "." . uniqid("", true) . "." . $fileCardBackgroundActualExtension;
$fileDestinationCardBackground = "../../img/card_background/" . $imageFullNameCardBackground;
$imageFullNameCardIcon = $newFileNameCardIcon . "." . uniqid("", true) . "." . $fileCardIconActualExtension;
$fileDestinationCardIcon = "../../img/card_logo/" . $imageFullNameCardIcon;
include 'connection.php';
if (empty($appName) && empty($appDescription) && empty($appGoogleGamesIcon)) {
header("Location: ../../admin/admin-main.php?upload=SelectedFields-MUST-NOT-BeEmpty");
exit();
} else {
$sql = "SELECT * FROM apps;";
$statement = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($statement, $sql)) {
echo "SQL statment failed";
} else {
mysqli_stmt_execute($statement);
$result = mysqli_stmt_get_result($statement);
$rowCount = mysqli_num_rows($result);
$sql = "INSERT INTO apps (appName, appDescription, appLinkFacebook, appLinkInstagram, appLinkPlaystore, appLinkWeb,
appGoogleGamesIcon, appFullImageNameBackground, appFullImageNameIcon) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
if (!mysqli_stmt_prepare($statement, $sql)) {
echo "SQL statment failed";
} else {
mysqli_stmt_bind_param(
$statement,
"sssssssss",
$appName,
$appDescription,
$appLinkFacebook,
$appLinkInstagram,
$appLinkPlaystore,
$appLinkWeb,
$appGoogleGamesIcon,
$appFullImageNameBackground,
$appFullImageNameIcon
);
mysqli_stmt_execute($statement);
move_uploaded_file($fileTempNameCardBackground, $fileDestinationCardBackground);
move_uploaded_file($fileTempNameCardIcon, $fileDestinationCardIcon);
header("Location: ../../admin/admin-main.php?upload=success");
}
}
}
} else {
echo "You have an error";
exit();
}
} else {
echo "Yopu need to upload a proper file type";
exit();
}
}
So to sum it up sql SELECT is working when I enter the data manually, images are where they are supposed to be under the right name and there are no errors.
Thanks :D
Found the problem by using this command above my sql statement. Everything works now.
Thanks for your help.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

query failedERROR: prepared statement "my_query" does not exist

Hello All
I'm trying to insert a form data into my postgreSQL DB in heroku through PHP and i tried all the solutions here but nothing solved my problem!. I can connect to the database but no operation worked well to me!. This error lead me to craziness!.
my code is:
<?php
$db_conn = pg_connect(" host="" port=5432 dbname="" user="" password="" ");
if(!$db_conn){
echo "Error : Unable to connect the database\n";
}
if (isset($_POST['savedata'])) {
$fn = $_POST ['fullname'];
$em = $_POST ['email'];
$ag = $_POST ['age'];
$ge = $_POST ['gender'] ;
$ci = $_POST ['city'] ;
$de = $_POST ['degree'];
$ex = $_POST ['experience'];
$jo = $_POST ['job'];
if($fn != "" and $em != "" and $ag != "" and $ge != "" and $ci != "" and $de != "" and $ex != "" and $jo != "") {
$data1="something to test";
$result = pg_prepare($db_conn, "my_query", "INSERT INTO members (fullname, email, age, gender, city, degree, experience, job) VALUES ($fn, $em, $ag, $ge, $ci, $de, $ex, $jo)");
$result = pg_execute($db_conn, "my_query", array($data1));
if (!$result){
error_reporting(E_ALL);
die("query failed".pg_last_error());
}
else {
echo "<script>";
echo "document.querySelector('.myalert').style.display = 'block';";
echo "setTimeout(function(){
document.querySelector('.myalert').style.display = 'none';
window.location.replace('home');
},5000);";
echo "</script>";
}
}
else {
echo "<script>";
echo "document.querySelector('.myalert1').style.display = 'block';";
echo "setTimeout(function(){
document.querySelector('.myalert1').style.display = 'none';
},2000);";
echo "</script>";
}
}
?>
You have syntax error in your code at the very first line.
Parse error: syntax error, unexpected '" port=5432 dbname="' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ')
There are also some other issues and oddities so it was just easier to rewrite some parts of your code.
I would also advice you to pay little more attention about the coding style, indentations and etc. It would be significantly easier to read and help you if the code were styled properly. PSR-2 Style Guide would be good place to start.
So here's the rewritten code, but note that I don't have PostgreSQL installed and that's why the code below isn't tested in any way. It should work, but there's also possibility that it doesn't.
See the comments in the code for further explanation.
// Change these credentials according to your needs, but without any quotes
$db_conn = pg_connect("host=localhost port=5432 dbname=mydb user=user password=pwd");
if (!$db_conn) {
die("Error : Unable to connect the database\n");
}
if (isset($_POST['savedata'])) {
$member_details = array(
$_POST['fullname'],
$_POST['email'],
$_POST['age'],
$_POST['gender'],
$_POST['city'],
$_POST['degree'],
$_POST['experience'],
$_POST['job']
);
}
// Iterates through the array and checks if there's any items of which has no proper value
foreach ($member_details as $key => $val) {
if (empty($val)) {
die($key . ' is empty.');
}
}
// Query inside single quotes, also variable names must be $1, $2, $3 etc
$query = 'INSERT INTO members (fullname, email, age, gender, city, degree, experience, job) VALUES ($1, $2, $3, $4, $5, $5, $7, $8)';
$result = pg_prepare($db_conn, "my_query", $query);
$result = pg_execute($db_conn, "my_query", $member_details);
if (!$result) {
// error actions
} else {
// success actions
}

Prevent users to edit eachother entries

I have a PHP script that allow users to register entries to a database. Entries are autoincremented. What I found out, is that user #A can get an entry from user #B by changing url from edit.php?id=2 to id=1.
Of course I want to prevent that. So my idea: if the user ID field in the mysql entry matches $_SESSION['user_id'] in my php script, editing is allowed.
A user should only be able to edit entries they have posted themselves.
What would be the best and most efficient way to achieve this?
<?php $bruker = $_SESSION['user_id']; ?>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$elv = htmlentities($_POST['elv'], ENT_QUOTES);
$vald = htmlentities($_POST['vald'], ENT_QUOTES);
$art = htmlentities($_POST['art'], ENT_QUOTES);
$dato = htmlentities($_POST['dato'], ENT_QUOTES);
$vekt = (int)$_POST['vekt'];
$lengde = (int)$_POST['lengde'];
$flue = htmlentities($_POST['flue'], ENT_QUOTES);
$gjenutsatt = (int)$_POST['gjenutsatt'];
$kjonn = (int)$_POST['kjonn'];
$bilde = htmlentities($_POST['bilde'], ENT_QUOTES);
$user = $_SESSION['user_id'];
// check that required fields are not empty
if ($elv == '' || $vald == '' || $art == '' || $dato == '' || $vekt == '' || $kjonn == '')
{
// if they are empty, show an error message and display the form
$error = 'Du må fylle ut de påkrevde feltene!';
renderForm($elv, $vald, $art, $dato, $vekt, $lengde, $flue, $gjenutsatt, $kjonn, $bilde, $user, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE fisk SET elv = ?, vald = ?, art = ?, dato = ?, vekt = ?, lengde = ?, flue = ?, gjenutsatt = ?, kjonn= ?, bilde = ?, user = ?
WHERE id=?"))
{
$stmt->bind_param("ssssiisiisii", $elv, $vald, $art, $dato, $vekt, $lengde, $flue, $gjenutsatt, $kjonn, $bilde, $user, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: /");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
Assuming your users have unique ID's you can simply add additional WHERE clause to your SQL:
if ($stmt = $mysqli->prepare("UPDATE fisk SET elv = ?, vald = ?, art =
?, dato = ?, vekt = ?, lengde = ?, flue = ?, gjenutsatt = ?, kjonn= ?,
bilde = ?, user = ?
WHERE id=? AND created_user = ?"))
Obviously replace created_user with the column you use to store the users ID who created the entry.
That way it will only ever update a row created by the user trying to edit it.
More securely, you could prevent them from ever seeing the page by first querying the created user id of the row in question then checking it against your user id $_SESSION as you suggest - then killing the script or redirecting them before it ever gets to the query.

Can't write to the database using INSERT INTO

I have written a form with server side validation using php and now my aim is to insert all the input's from my form into my database (which already has its tables). Below is my syntax:
//Example of one of my validations (for postcode input)
if (empty($_POST["postcode"])) {
$postcodeErr = "";
} else {
$postcode = test_input($_POST["postcode"]);
if(!preg_match("/^[0-9]*$/", $postcode)) {
$postcodeErr = "Only numeric characters";
}
else if (strlen($postcode) != 4) {
$postcodeErr = "Must be 4 digits in length";
}
}
}
//Connect to database server
$conn = mysql_connect("localhost", "-----", "------");
mysql_select_db("-------", $conn)
or die ('Database not found ' . mysql_error() );
// The SQL statement is built
$sql = "INSERT INTO Customer (name, address, suburb, state, postcode)
VALUES ('$_POST[name]', '$_POST[address]', '$_POST[suburb]', '$_POST[$state]', '$_POST[postcode]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn)
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //end of my php tag
When I run my form, I get a parse error saying that I have an unexpected T_FUNCTION. I know there is a lot above (tried to make it as simple as I can) but I can't seem to word around fixing the error and if I do, I just get another error. Am I writing the code correctly? Normally it's best when other people look at your work. Help will be much appreciated!
The quotes for $_POST['name'] and all other variables was missing in the post variable.
Try with
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$sql = "INSERT INTO Customer (name, Address, suburb, state, postcode)
VALUES ('$name', '$address', '$suburb', '$state', '$postcode')";
you also have one extra brace above database connection, use mysqli prepared statements for better security.
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "failed to connect to the database"; die();
}
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$stmt = $db->prepare("insert into `Customer` (name, Address, suburb, state, postcode) VALUES (?,?,?,?,?)";
$stmt->bind_param('sssss', $name, $address, $suburb, $state, $postcode);
$stmt->execute();
echo $stmt->affected_rows."record added";
mysql_close($conn) Needs to have a ; after it...
That's why the function after it is unexpected
Agreed with Fred, there seems to be an extra ending brace just above //Connect to database server which is breaking the code.
If that doesn't fix it, please copy/paste your full error message.
EDIT:
else if (strlen($postcode) != 4) {
needs to be
} else if (strlen($postcode) != 4) {
And there are two extra braces at the end of that if statement (just above the //Connect to database server)

mysql_insert_id(); keeps returning '0'

I'm trying to grab the id after a query using mysql_insert_id();, but I'm still getting 0 despite the fact that
I've placed it after the query itself and
I've made sure that the id (called P_Id) has AUTO_INCREMENT.
Code below:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
$idit = mysql_insert_id();
echo $idit;
if (mysqli_query($con,$sql))
{
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Thinking "Oh okay maybe I have to actually query it first", I did the following but came up with the same result:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
if (mysqli_query($con,$sql))
{
$idit = mysql_insert_id();
echo $idit;
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Any idea where I went wrong? I've gone through other threads but nothing seems to be working for me. Thanks in advanced.
EDIT: I have changed mysql_insert_id(); to mysqli_insert_id(); and this time it didn't even return a 0, just blank.
EDIT 2: Thank you mbouzahir - your solution worked :)
Tried using mysqli_insert_id($con) instead of mysql_insert_id() in your second example?
Your query is vulnerable to SQL injection. You should be using prepared statements with parameter binding. Try this (and yes, I'm using the OOP API because it's a damn site cleaner)
$con = new mysqli(-connectiondetails-);
if ($con->connect_errno) {
throw new Exception($con->connect_error, $con->connect_errno);
}
$stmt = $con->prepare(
'INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
if ($stmt === false) {
throw new Exception($con->error);
}
// you should probably check here that all required POST params are present
$stmt->bindParam('sssssssssss',
$_POST['name'],
$_POST['email'],
$_POST['address'],
$_POST['phone'],
$_POST['date'],
$_POST['service'],
$_POST['extra1'],
$_POST['extra2'],
$_POST['extra3'],
$_POST['extra4'],
$_POST['extra5']);
if (!$stmt->execute()) {
throw new Exception($stmt->error);
}
echo $con->insert_id;
Try this one
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
if (mysqli_query($sql,$con))
{
$idit = mysqli_insert_id();
echo $idit;
}
else
{
echo "Error message goes here: " . mysql_error($con);
}

Categories