Multiple INSERT not working - php

I have multiple If statements that if true, inserts data into the db. The Problem is that the 2nd one of the INSERT statements inserts it 4 times. How would i stop it from adding duplicates. Also the returned $_POST['tshirt'] contains only one value which is being inserted 4 times.
if(isset($_POST['distance'])) {
$dist = $_POST['distance'];
$sql="INSERT INTO sportevent_parameters.Distance(value, user_ref, event) VALUES ('$dist', '$id', '$event')";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
if(isset($_POST['tshirt'])) {
$tshrt = $_POST['tshirt'];
$sql="INSERT INTO sportevent_parameters.T_Shirt(value, user_ref, event) VALUES ('$tshrt', '$id', '$event') ON DUPLICATE KEY UPDATE";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
if(isset($_POST['partnerid'])) {
$sql="INSERT INTO sportevent_parameters.Partner_ID(value, user_ref, event) VALUES ('$partnerid', '$id', '$event')";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
if(isset($_POST['racecategory'])) {
$sql="INSERT INTO sportevent_parameters.Race_Category(value, user_ref, event) VALUES ('$category', '$id', '$event')";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
What would cause it to insert multiple copies into the DB?

Firstly, please sanitise your user input before using it directly in a query!!! - also read this.
Secondly - the problem is that your calls to mysql_query() should be inside the if statements. With what you have done, mysql_query() is executed regardless, only the SQL statement itself is changed by the if. This means that if the first if condition is true, but all the others are false, the first statement will be executed 4 times.
Change your code to:
if (isset($_POST['distance'])) {
$dist = mysql_real_escape_string($_POST['distance']);
$sql = "INSERT INTO sportevent_parameters.Distance(value, user_ref, event) VALUES ('$dist', '$id', '$event')";
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
}
// etc etc

Edit: The mysql_query's should be inside the if statements so it does not get called if the if is not called. I would also check the variables you are passing.
Multiple SQL statements in one query are not supported in PHP. You have to split up each SQL statement into separate queries to the database.
Link to PHP Manual: http://php.net/manual/en/function.mysql-query.php

Related

Problems with mysqli_query function [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 7 years ago.
i'm new to PHP and MySQL. I'm having issues with one of my mysqli_query functions. I have a database connection that works perfectly as the first half of my php file actually stores data into certain tables of the database.
The problem starts when i want to perform another query against the database. Here's the code:
// INSERT statements.
$queryMember = "INSERT INTO member (surname, name, gender, email, telHome, telMobile, dob, studentNum, idNum) VALUES ('$sur_name', '$f_name', '$gender', '$email', '$tel_home', '$mobile_num', ,'$date_of_birth', '$studentNumber', '$id_number')";
$queryAddress = "INSERT INTO physicalDetails (houseNum, unitNum, streetAdd, suburb, city, province, code ) VALUES ('$house_number', '$unit_number', '$street_address', '$suburb_name', '$city_name', '$province_name', '$zip_code')";
$queryStaff = "INSERT INTO staff (staffID ) VALUES ('$staff_id')";
$queryStudent = "INSERT INTO student (major ) VALUES ('$student_major')";
// Statements that must query the database.
$resultMember = mysqli_query($dbc, $queryMember) or die ('Error while inserting data into member details table');
$resultAddress = mysqli_query($dbc, $queryAddress ) or die ('Error while inserting data into member physical details table');
$resultStaff = mysqli_query($dbc, $queryStaff ) or die ('Error while inserting data into staff information table' );
$resultStudent = mysqli_query($dbc, $queryStudent ) or die ('Error while inserting data into student major details table');
mysqli_close($dbc);
When i run my form, my first error is the following: "Error while inserting data into member details table".
I don't understand why it's giving me an error. Any advice or suggestions would be appreciated. :)
Don't output a fixed (and useless) error message: Have the DB tell you what you did wrong:
$resultMember = mysqli_query($dbc, $queryMember) or die (mysqli_error($dbc));
^^^^^^^^^^^^
If you had that, you'd have been told about your syntax errors:
$queryMember = "[..snip..], '$mobile_num', ,'$date_of_birth', '$studentNumber', '$id_number')";
^^^^

Having hard time querying database

I'm trying to insert data in mysql using php I have FK with parishionerID
my query is correct but I always get the Error querying database. It doesn't show me
the specific query that I'm having an error with. BapID is PK. Hope you can help me resolve this. Thanks.
$con = mysqli_connect('localhost', 'root', '', 'RMS') or die('Error connecting to MySQL server');
$sql="INSERT INTO baptismal (ParishionerID, BapID, Datebaptism, Ministerbaptism, Sponsor, Sponsor2, Volume, Page)
VALUES('$id', NULL, '$Datebap', '$Ministerbap', '$Sponsor', '$Sponsor2, '$Volume', '$Page')";
$result = mysqli_query($con, $sql) or die('Error querying database.');
mysqli_close($con);
If I input datas in mysql manually this is the query which is pretty have the same with my query.
INSERT INTO `rms`.`baptismal` (`ParishionerID`, `BapID`, `Datebaptism`, `Ministerbaptism`, `Sponsor`, `Sponsor2`, `Volume`, `Page`) VALUES ('80', NULL, '2014-07-16', '131', 'sdasd', '123123', '123123', '123');
There seems to be only Syntax error. Youre missing '
VALUES('$id', NULL, '$Datebap', '$Ministerbap', '$Sponsor', '$Sponsor2, '$Volume', '$Page')";
----------------------------------------------------------------------^
Your $Sponsor2 is not properly quoted.
FYI: Let the script print out the error SQL too.
Convert your line as:
$result = mysqli_query($con, $sql) or die('Error querying database: '.$sql);
Then, you will see the exact query that ran.
Do not print SQLs on the server mode.

Failure when inserting data to DB through php

So I have this exercise where i need to insert (and do various other actions, i did those successfully) data into a very basic database through php insertion, but I don't seem to be able to do so, and I have absolutely no idea why.
Here is my code (disclaimer, i'm only at the beginning of learning php, so any advice would be really appreciated!):
<?php
include 'Connect.php';
$query = "INSERT INTO game ( product_id, product_name, multiplayer, pegi, genre, release_date, dis_id, dev_name)
VALUES ('"
.$_POST['product_id']."','"
.$_POST['product_name']."','"
.$_POST['multiplayer']."','"
.$_POST['pegi']."','"
.$_POST['genre']."',"
.$_POST['release_date'].",'"
.$_POST['publisher'].",'"
.$_POST['developer']."')";
//execute query
$queryexe = mysql_query($query);
if ($queryexe) {
mysql_query("COMMIT");
print("<p><font size=\"+1\">Success!</font></p>");
} else {
print("<p><font size=\"+1\">Error</font></p>");
}
//disconnect from database
mysql_close($connectionstring);
?>
It connects to the db, as I'm able to see what's in the game table, but i don't know why i'm getting a constant error.
Thanks in advance!
Here is your code modified since that transaction was incomplete
include 'Connect.php';
mysql_query("START TRANSACTION");
$query = "INSERT INTO game ( product_id, product_name, multiplayer, pegi, genre, release_date, dis_id, dev_name)
VALUES ('"
.$_POST['product_id']."','"
.$_POST['product_name']."','"
.$_POST['multiplayer']."','"
.$_POST['pegi']."','"
.$_POST['genre']."','"
.$_POST['release_date']."','"
.$_POST['publisher']."','"
.$_POST['developer']."')";
//execute query
$queryexe = mysql_query($query);
if ($queryexe) {
mysql_query("COMMIT");
print("<p><font size=\"+1\">Success!</font></p>");
} else {
mysql_query("ROLLBACK");
print("<p><font size=\"+1\">Error</font></p>");
}
//disconnect from database
mysql_close($connectionstring);
You were doing a commit, without beggining a transaction, and no rollback in case of mysql error or failure,
As a recommendation, start working with mysqli and don't use your values concatenated in the insert statement.
Edit
You are missing a quote after the double quote in publisher field
.$_POST['release_date'].",'"
.$_POST['publisher']."' // <--- this one

mysql_insert_id() not returning a value -

I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...

Insert into two tables from a single form

Insert into two tables from a single form. The first insert go in fine the second generates this error Duplicate entry '0' for key 1 any idea what is happening?
$connection=mysql_connect ("localhost", "foo", "bar") or die ("I cannot connect to the database.");
$db=mysql_select_db ("database", $connection) or die (mysql_error());
$query = "INSERT INTO worklog (id, newtime, datetime, clientname, clientcode, startmo, startday, startyr, endmo, endday, endyr, duemo, dueday, dueyr, market, job, allTypes, spec, status, designer, dsgnemail, adrep, ademail, frame1, frame2, frame3, rush) VALUES ('$id', $newtime, now(), '$clientname', '$clientcode', '$startmo', '$startday', '$startyr', '$endmo', '$endday', '$endyr', '$duemo', '$dueday', '$dueyr', '$market', '$job', '$allTypes', '$spec', '$status', '$designer', '$dsgnemail', '$adrep', '$ademail', '$frame1', '$frame2', '$frame3', '$rush')";
$sql_result = mysql_query($query, $connection) or die (mysql_error());
$worklog_id=mysql_insert_id($connection);
$connection2=mysql_connect ("localhost", "foo", "bar") or die ("I cannot connect to the database.");
$db2=mysql_select_db ("database", $connection2) or die (mysql_error());
$query2 = "INSERT INTO worklognotes (worklog_id, spec) VALUES ('$worklog_id', '$spec')";
$sql_result = mysql_query($query2, $connection2) or die (mysql_error());
I thin the culprit is the line:
$worklog_id=mysql_insert_id($connection);
according to the PHP documentation:
"The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established"
So if the id in worklog is not AUTO_INCREMENT it will always return 0 ... your second attempt at running the code will cause:
Duplicate entry '0' for key 1
Two ways to fix this:
id for worklog should be AUTO_INCREMENT ... this way mysql_insert_id will return ther ID generated by the database and you can use it as a working id for the next query
just use $id instead of $worklog_id
normally with and table ID column you set it to auto-increment and never explicitly insert it. The database management system will take care of inserting that column. The error means that you are inserting a row that has that ID already, meaning the column has a UNIQUE constraint.

Categories