Basic insert into SQL - php

I know this is really simple i haven't touched PHP and SQL in a few years.
This works
$mysqli->query("INSERT INTO sonyCES2013.registration (id,
firstName, lastName, eMail, telephone, outlet, comfirm,
preferTime, date) VALUES (NULL,Cat, 'Catherine',
'Cat#gmail.com', '123-456-4561', 'Some Text', 'Yes', '4:00pm'
,'1/09/14')");
this doesn't work
$mysqli->query("INSERT INTO sonyCES2013.registration (id,
firstName, lastName, eMail, telephone, outlet, comfirm,
preferTime, date) VALUES
(NULL,{$fName},{$lName},{$eMail},{$telephone},{$outlet},{$comfirmation},{
$preferTime},{$day})");
help and yes i did check that the variables aren't empty and i did try without the `` between each {}

You need to add ' ' to the variables to make the interpeter able to understand what you are trying to do ( in this case passing some php variable as parameters)
Use this and see if it works:
$mysqli->query("INSERT INTO sonyCES2013.registration (id, firstName, lastName,
eMail, telephone, outlet, comfirm, preferTime, date) VALUES
(NULL,'$fName','$lName','$eMail','$telephone','$outlet',
'$comfirmation','$preferTime','$day')");

It won't work that way because the resulting SQL looks something like this:
$mysqli->query("INSERT INTO sonyCES2013.registration (id, firstName, lastName, eMail, telephone, outlet, comfirm, preferTime, date) VALUES (NULL,Cat, Catherine, Cat#gmail.com, 123-456-4561, Some Text, Yes, 4:00pm ,1/09/14)");
Note the lack of single quotes around the strings, which make the SQL invalid.

Related

Error in executing insertion query

Isn't this query correct?
$insert = INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10');
I got following error, please help I am a beginner.
Parse error: syntax error, unexpected 'INTO' (T_STRING) in
C:\xampp\htdocs\google.php on line 9
$insert = "INSERT INTO `geninfo` (`S.N`, `Name`, `Address`, `DOB`) VALUES ('Suresh','Ratnanagar','Missing address here','1989/04/10');";
Note that I have also corrected your MySQL query. S.N refers to the column named N on the table named S, which I'm pretty certain is not what you wanted.
Also I just realised you have four columns, but only three values. Fixed that too.
You have no quotes, it should be like this:
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10')";
upd
It seems you are storing date of birth as a string, not as a timestamp (or similar) which is not a good idea
You need to give a (NULL or '') for the S.N field and quotes should be given before and after each and every value.
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES
('', 'Suresh','Ratnanagar','1989/04/10')";
Moreover the field name S.N could create problems. Let me know if this works.
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10')";

PHP mysqli does not insert into database

I am very familiar with PHP, but this is my first time using the mysqli library. I am trying to insert a row into the database and it just does not insert. My code look like this (database login details changed for security):
... // $_REQUEST variables processed
$oConn = new mysqli("localhost","user","password","mydatabase") or die("Error " . mysqli_error($oConn));
$rProvider = $oConn->query("select * from providers where id = $iProviderID");
$aProvider = mysqli_fetch_array($rProvider);
// $aProvider has all the information from the provider that I wanted, so my database connection is working
$oConn->query("insert into bookings (provider_id, provider_rates_id, secret, preferred_date, alternate_date, adults, children, transfer_required, firstname, lastname, email, phone, comments) values
($iProviderID, $iRatesID, $sSecret, '$sDate', '$sAltDate', $iAdults, $iChildren, $iTransfer, '$sFirstNameSQL', '$sLastNameSQL', '$sEmailSQL', '$sPhoneSQL', '$sCommentsSQL'");
$iBookingID = $oConn->insert_id;
I am getting no error and $iBookingID is 0. The row just doesn't get inserted into the database. I have gone through the PHP manual and similar posts on StackExchange, but have not been able to resolve this issue.
typo-u forgot to add single quotes and also a bracket.
$oConn->query("insert into bookings (provider_id, provider_rates_id, secret, preferred_date, alternate_date, adults, children, transfer_required, firstname, lastname, email, phone, comments) values
('$iProviderID', '$iRatesID', '$sSecret', '$sDate', '$sAltDate', '$iAdults', '$iChildren', '$iTransfer', '$sFirstNameSQL', '$sLastNameSQL', '$sEmailSQL', '$sPhoneSQL', '$sCommentsSQL')");
... // $_REQUEST variables processed
$oConn = new mysqli("localhost","user","password","mydatabase") or die("Error " . $oConn->error);
$oConn->query("insert into bookings (provider_id, provider_rates_id, secret, preferred_date, alternate_date, adults, children, transfer_required, firstname, lastname, email, phone, comments) values
('$iProviderID', '$iRatesID', '$sSecret', '$sDate', '$sAltDate', '$iAdults', '$iChildren', '$iTransfer', '$sFirstNameSQL', '$sLastNameSQL', '$sEmailSQL', '$sPhoneSQL', '$sCommentsSQL')");
$iBookingID = $oConn->insert_id;
echo $iBookingID;
there's a typo on your code, you're missing to close the ")" of the values part of your query.
The correct, query:
$oConn->query("insert into bookings (provider_id, provider_rates_id, secret, preferred_date, alternate_date, adults, children, transfer_required, firstname, lastname, email, phone, comments) values ($iProviderID, $iRatesID, $sSecret, '$sDate', '$sAltDate', $iAdults, $iChildren, $iTransfer, '$sFirstNameSQL', '$sLastNameSQL', '$sEmailSQL', '$sPhoneSQL', '$sCommentsSQL');");
If this is not a php error, you can try using echo $oConn->error to get mysql query error!

SQL / PHP Insert columns form one table to another

Hi I working on simple newsletter script, I got two groups there with two different tables for each group.
I want to move subscribers from one group to another, I put this query and It works:
$sql = "INSERT INTO newsletter_subscribers2 SELECT * FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
However after moving some previous subscribers I got error with duplicated entry key, as I supose query is moved with ID, so I want just move, name, lastname and email.
$sql = "INSERT INTO newsletter_subscribers2 VALUES (firstname, lastname, email) SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname, newsletter_subscribers.email FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
However this part of code doesnt seemst to work as I got syntax error, can anyone help me with this I will be very happy.
Thanks for reply
You have to remove values
$sql = "INSERT INTO newsletter_subscribers2(firstname, lastname, email)
SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname,
newsletter_subscribers.email
FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
Remove the VALUES
$sql = "INSERT INTO newsletter_subscribers2 (firstname, lastname, email)
SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname,
newsletter_subscribers.email
FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";
Edit: And always use mysql_real_escape_string to prevent SQL-injection:
$sql = "... WHERE id='".mysql_real_escape_string($_GET['nid'])."'";
Try this:
insert into newsletter_subscribers2 (col1, col2, col3, etc) select col1, col2, etc from newsletter_subscribers2 where 1 = 1

How to handle nulls in this PHP/mysql insert statement

I sometimes have arrays with null or empty values. In MySql they are set up to be non-nullable, but they have default values assigned. Why then, does MySql give me an error, e.g. Column user_type can not be null. (I'm not running in strict mode).
I realise that I could use the keyword DEFAULT in place of some values when preparing the query, but I don't really want to do that. I would like to be able to write my SQL statements verbatim, rather than put them together with foreach loops, etc. For example, I would like to use "INSERT INTO users (user_type, first_name, last_name, password) VALUES (:user_type, :first_name, :last_name, :password)";
As far as I recollect, this was working fine (i.e. substituting in the correct defaults) until I moved from using ? query markers to named parameters...
Thanks...
I would create a function that accepts the values as parameters. It would have the default values in an associative array. If the value for any of the parameters is null, it would replace it with the default.
eg
function setUpQuery($user_type_in, $first_name_in, $last_name_in, $password_in){
$default_values('user_type' => 'Admin', 'first_name' => 'John', 'last_name' => 'Doe', 'password' => 'XXX');
$user_type = ($user_type_in == NULL)? $default_values['user_type']:$user_type_in;
.....
return "INSERT INTO users (user_type, first_name, last_name, password) VALUES ('$user_type', '$first_name', '$last_name', '$password');"
}
Good Point. How about the following:
INSERT INTO users(user_type, first_name, last_name,password) values
(ifnull('$user_type',default(user_type)), ifnull('$first_name', default(first_name)),
ifnull('$last_name',default(last_name)), ifnull('$password', default(password));

postgres enum insertion using pg_query

I have a table with one field of enum type. I execute the following query using pg_query
INSERT INTO users (email, facebook_id, first_name, middle_name, last_name, birth_date, password, gender, school_id, timezone, email_verified, role_id) VALUES ('robert#1599309412.com', NULL, 'Robert', '', 'George', '1984-05-20', 'Some password', 'MALE', 1, '0.0', false, 1 );
pg_query($connection, 'INSERT INTO users (email, facebook_id, first_name, middle_name, last_name, birth_date, password, gender, school_id, timezone, email_verified, role_id) VALUES (\'robert#2084537193.com\', NULL, \'Robert\', \'\', \'George\', \'1984-05-20\', \'Some password\', \'MALE\', 1, \'0.0\', false, 1 )')
but i get error as below.
PHP Warning: pg_query(): Query failed: ERROR: invalid input value for enum sex: "MALE"
LINE 1: ...rt', '', 'George', '1984-05-20', 'Some password', 'MALE', 1,...
Direct execution of query in postgres client don't give this error.What is solution for this?
Please make sure cases match. Postgres is not too strict about it (consider the table names), but it might worth a check.
Having a gender attribute enum'd is unnecessary overhead in my opinion, you're better off having a male int column with 1, 0 values and maybe null for unknown/not specified. With values greater than 1 it's still future-proof just in case a new gender appears. :)
If you really are attached to enums, you might want to consider using PDO, because it makes binding values a lot easier and a lot more secure.

Categories