I have the follow query
INSERT
INTO
profile(
fullname,
email,
cpfcnpj,
identity,
phone,
cellphoneone,
cellphonetwo,
birthday,
cep,
address,
)
VALUES(
: fullname, : email, : cpfcnpj, : identity, : phone, : cellphoneone, : cellphonetwo, : birthday, : cep, : address
);
SELECT
LAST_INSERT_ID() AS lid;
PHP Code
$insertProfile = $database->driver()->prepare("
INSERT INTO wordprofile (fullname, email, cpfcnpj, identity, phone, cellphoneone, cellphonetwo, birthday, cep, address, city, state, reference, number, pay, contract) VALUES (:fullname, :email, :cpfcnpj, :identity, :phone, :cellphoneone, :cellphonetwo, :birthday, :cep, :address, :city, :state, :reference, :number, :pay, :contract); SELECT LAST_INSERT_ID() as lid;"
);
$insertProfile->bindValue(":fullname", $arg["name"]." ". $arg["lastname"]);
$insertProfile->bindValue(":email", $arg["email"]);
$insertProfile->bindValue(":cpfcnpj", $arg["cpfcnpj"]);
$insertProfile->bindValue(":identity", $arg["rg"]);
$insertProfile->bindValue(":phone", $tel);
$insertProfile->bindValue(":cellphoneone", $arg["cel1"]);
$insertProfile->bindValue(":cellphonetwo", $cel2);
$insertProfile->bindValue(":birthday", $birthday);
$insertProfile->bindValue(":cep", $arg["zip"]);
$insertProfile->bindValue(":address", $arg["address"]);
$insertProfile->execute();
$lastid = $insertProfile->fetch()[0];
echo $lastid; //nothing, if change to var_dump returns false
It works properly when i run into phpmyadmin or mysql prompt. However that same query returns false in PHP; that insert works, only SELECT LAST_INSERT_ID() AS lid; does not returns.
It doesn't work actually because PDO doesn't support several queries executed in one statement.
You have to make another execute with a separated query or use the method lastInsertId() as mentioned in the comments by Frederic.
Related
I have two tables, user_info and Friend_info. I want to do that when user update his record in user_info then it should also b update in friend_info where friend_id=user_id. I have tried this
UPDATE user_info (name, user_email, Gender, DOB, contact, address) WHERE user_id='$user_id',
friends_info(name, user_email, Gender, DOB, contact, address) WHERE friend_id='$user_id'
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address');
But its not working . Any other solution please. It'll be appreciated.
I know this question is too late to ask now a days but its my problem because i am confused after doing so many search and no query is working in my case.
Your question is not clear. So are you testing something like you want query in phpmyadmin. if not then you might need to do in as a transaction. but if its a test or such try this:
UPDATE user_info (name, user_email, Gender, DOB, contact, address)
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address')
WHERE user_id='$user_id';
UPDATE friends_info(name, user_email, Gender, DOB, contact, address)
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address')
WHERE friend_id='$user_id';
So this is two query which then they are gonna execute together. But now in PHP
check these:
https://stackoverflow.com/a/802474/2226796
http://se2.php.net/manual/en/mysqli.multi-query.php
PHP + MySQL transactions examples
You can join the two tables in your statement using user_id as the joining key.
UPDATE user_info ui
INNER JOIN friends_info fi
ON ui.user_id = fi.user_id
SET ui.name = $name,
SET ui.user_email = $email,
SET ui.Gender = $Gender,
SET ui.DOB = $DOB,
SET ui.contact = $contact,
SET ui.address = $address,
-- set friends_info
SET fi.name = $name,
SET fi.user_email = $email,
SET fi.Gender = $Gender,
SET fi.DOB = $DOB,
SET fi.contact = $contact,
SET fi.address = $address
WHERE ui.user_id = $user_id;
According to everything I've found and seen, this seems correct. When I print $query the outcome is the following:
"INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (?,?,?,?,?,?,?,?,?)"
The parameters should have been filled in with the variables in bindValues(). So, for example ...
INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (Bill, A, Hopkins, 123 Ave, ....)
I'd like to stick with this method - it is surrounded by a try/catch block. From printing the query variable out I can see that is where the issue is.
What am I missing? I really appreciate you looking!
$query = 'INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (?,?,?,?,?,?,?,?,?)';
echo $query;
$statement = $db->prepare($query);
$statement->bindValue(1, $firstName);
$statement->bindValue(2, $middle);
$statement->bindValue(3, $lastName);
$statement->bindValue(4, $address);
$statement->bindValue(5, $city);
$statement->bindValue(6, $state);
$statement->bindValue(7, $zip);
$statement->bindValue(8, $email);
$statement->bindValue(9, $gender);
$success = ($statement->execute());
We need more code considering the error but you can try this with prepared statements:
$query = 'INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (:firstName, :middle, :lastName, :address, :city, :state, :zip, :email, :gender)';
$statement = $db->prepare($sql);
$statement->execute(array(':firstName'=>$firstName, ':middle'=>$middle, ':lastName'=>$lastName, ':address'=>$address, ':city'=>$city, ':state'=>$state, ':zip'=>$zip, ':email'=>$email, ':gender'=>$gender));
I've following SQL query which is working absolutely fine .
$sql = "INSERT INTO user_login (user_id, email, password, token)
VALUES ($user_id, '$email', '$user_password', '$token')";
Now I've added two new fields to the respective table called 'token_creation_time' and 'token_last_accessed_time'. These fields will contain the current time values(i.e. UNIX Time stamp values). For this purpose I used time() function from PHP in the SQL query as follows but it didn't work. I don't know where I'm making a mistake.
$sql = "INSERT INTO user_login (user_id, email, password, token, token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', time(), '')";
The last two field's structure in MySQL DB is as follows :
Name : token_creation_time
Type : int(10)
Collation :
Attributes :
Null : No
Default : None
Extra :
Name : token_last_accessed_time
Type : int(10)
Collation :
Attributes :
Null : No
Default : None
Extra :
In my query I want to insert the current time stamp value only into the field 'token_creation_time'.
Thanks.
Just change the Null:No to Null:Yes,it should work
Name : token_last_accessed_time
Type : int(10)
Collation :
Attributes :
Null : Yes
Default : None
Extra :
I had encountered same error in postgresql when i try to insert an empty string '' for timestamps, so i use nullif function to overcome this:
NULLIF(?, '')
i think mysql has same function
AND make sure your column is nullable
You cannot use php time() function inside query.
Either concatenate this:
$sql = "INSERT INTO user_login (user_id, email, password, token, token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', ".time().", '')";
Or use mysql function UNIX_TIMESTAMP():
$sql = "INSERT INTO user_login (user_id, email, password, token, token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', UNIX_TIMESTAMP(),
'')";
You're inserting a literal string containing time() there.
$sql = "INSERT INTO user_login (user_id, email, password, token,
token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', time(), '')";
error here ^^^^^^
either a) use string concatenation to insert the actual timestamp.
$sql = "INSERT INTO user_login (user_id, email, password, token,
token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', " . time() . ", '')";
b) use pdo with a prepared statement (strongly preferred no matter what) to avoid sql injection attacks, or c) use mysql UNIX_TIMESTAMP() function instead of php time.
$sql = "INSERT INTO user_login (user_id, email, password, token,
token_creation_time, token_last_accessed_time)
VALUES ($user_id, '$email', '$user_password', '$token', UNIX_TIMESTAMP(), '')";
a good way to debug this is to print the query statement out before you execute it, and then run it against the database directly, it will no doubt give you an error above shoving a string into an int or an unknown column
Change your table structure and set NULL attribute to Yes. It will work fine :)
Use now() replace with time() it may work.
I am working on building an employee database but seem to have run into an interesting issue.
When I run my query to add a new user/employee, I get the error:
Column count doesn't match value count at row 1
From what I have researched, this seems to be an error with inserting more/less values than what is declared in the first part of an insert statement example:
INSERT INTO table (col1, col2) VALUES (val1, val2, val3)
The thing is though, I have looked over my query and the columns and values match perfectly (count wise). I have even looked for things in my query such as missing quotes, commas, etc.
Here is my code (query):
$db->query("INSERT INTO userdata (
Username,
Email,
Phone,
Password,
FirstName,
LastName,
Address,
City,
State,
Zip,
JobTitle,
UserGroup,
JobStatus,
Points,
Status,
BirthDate,
HireDate,
HourlyRate,
DateAdded,
SSN
) VALUES (
'$Username',
'$Email',
'$Phone',
'$Password',
'$FirstName',
'$LastName',
'$Address',
'$City',
'$State',
'$Zip',
'$JobTitle',
'$Group',
'$JobStatus',
0,
'$Status',
'$BirthDate',
'$HireDate',
'$HourlyRate'
'$TodaysDate',
'$SSN'
)") or die(mysqli_error($db));
Some things to note:
This not all of the columns in the table have data inserted here (I think its possible to do this and things such as auto incrementing ID's will fill themselves in and others will be left blank)
From the variable dumps I have done, all of these variables are valid.
I am really confused about this and any help would be appreciated.
Check the following portion again:
INSERT INTO userdata(...,
JobStatus,
UserGroup,
Points,
UserGroup,
Status,
.....
,)VALUES(...,
$JobStatus',
0,
'$Group',
'$Status',
......
)
In values(, ?, ?, ?), after jobstatus, there should be UserGroup and then Points. And UserGroup appeared twice.
I am inserting a record and i want to use the id of the last record inserted.
This is what i have tried:
$sql = 'INSERT INTO customer
(first_name, last_name, email, password,
date_created, dob, gender, customer_type)
VALUES(:first_name, :last_name, :email, :password,
:date_created, :dob, :gender, :customer_type)'
. ' SELECT LAST_INSERT_ID()' ;
I am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()'.
Can anyone show me where is my mistake?
Thanks!
Check out mysql_insert_id()
mysql_query($sql);
$id = mysql_insert_id();
When that function is run after you've executed your INSERT statement in a mysql_query() command its result will be the ID of the row that was just created.
You can do another query:
$last_id = "SELECT LAST_INSERT_ID()";
Or try to add ; in your query:
INSERT INTO customer
(first_name,
last_name,
email,
password,
date_created,
dob,
gender,
customer_type)
VALUES(:first_name,
:last_name,
:email,
:password,
:date_created,
:dob,
:gender,
:customer_type)<b>;</b>' . ' SELECT LAST_INSERT_ID()';