php insert mysql_query get id - php

In PHP 4, how can I easily get the last id after an insert in db?
For example:
$queryInsert = "INSERT INTO `table` (`id`, `info`) VALUES (NULL, '".$INFO_VAR."');";
mysql_query($queryInsert) or die (mysql_error());

use mysql_insert_id();, you find the doc here

Related

MySql connect. What to do?

I am really new to php and I am trying to use simple insert to my mysql database from the form.
I know that this mysql connection/insertion is dangerous and not used anymore. so can anyone please help me with this simple thing? I tried to google, but nothing is working so far :/
<?
$text=$_POST['name'];
$text=$_POST['surename'];
mysql_connect("localhost", "db_name", "pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$result = mysql_query("INSERT INTO `table` (name, surename)
VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Maybe change
$text=$_POST['name'];
$text=$_POST['surename'];
to
$name = $_POST['name'];
$surename = $_POST['surename'];
PS: And also your column names don't match your values. Your query, after inserting params
"INSERT INTO `table` (name, surename) VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')"
will probably look like this
INSERT INTO `table` (name, surename) VALUES (NOW(), 'Jhon', 'Wick')
As you can see there's name, surename (which probably should be surname) and (NOW(), 'Jhon', 'Wick'). So either add a column (if you have that column in your database):
INSERT INTO `table` (created_at, name, surename) VALUES (NOW(), 'Jhon', 'Wick')
or remove NOW() from your values
INSERT INTO `table` (name, surename) VALUES ('Jhon', 'Wick')

Insert PHP array and string in MySQL query

I have the following query which is working fine in inputting the arrays $stid and $attendance_status. However, I also want to populate the column called SCH_TIMESLOT with a fixed number 22 or eventually a string value which is the same for all records. I am getting an error stating:
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 '22' at line 2
This is my query:
for($i=0;$i<count($attendance_status);$i++){
mysql_query("INSERT INTO `ATTENDANCE` (`ID`, `STUDENT_ID`, `ATTENDANCE`, `SCH_TIMESLOT`) VALUES
(NULL, $stid[$i], $attendance_status[$i]), 22") or die (mysql_error());
Thank you for your help
You have missed out 22 from your VALUES brackets. It has to be inside.
<?php
for($i=0;$i<count($attendance_status);$i++){
mysql_query("INSERT INTO `ATTENDANCE` (`ID`, `STUDENT_ID`, `ATTENDANCE`, `SCH_TIMESLOT`) VALUES
(NULL, $stid[$i], $attendance_status[$i], 22)") or die (mysql_error());
You have a syntax error.
$stid[$i], $attendance_status[$i]), 22") you are closing the brackets before 22
Try it like this
"INSERT INTO `ATTENDANCE` (`ID`, `STUDENT_ID`, `ATTENDANCE`, `SCH_TIMESLOT`)
VALUES
(NULL, $stid[$i], $attendance_status[$i], 22)"
Try this, i replace ")" before "22" and move it after.
for($i=0;$i<count($attendance_status);$i++){
mysql_query("INSERT INTO `ATTENDANCE` (`ID`, `STUDENT_ID`, `ATTENDANCE`, `SCH_TIMESLOT`) VALUES
(NULL, $stid[$i], $attendance_status[$i], 22)") or die (mysql_error());
Change your sql query as below
for($i=0;$i<count($attendance_status);$i++){
mysql_query("INSERT INTO `ATTENDANCE` (`ID`, `STUDENT_ID`, `ATTENDANCE`, `SCH_TIMESLOT`) VALUES `(NULL, $stid[$i], $attendance_status[$i], 22") or die (mysql_error());`

INSERT INTO runs only 1 time?

Here's my code:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
the first time, I could see the the values were added but when I reloaded, it didn't do any more, is it supposed to be like this ?
So if I want it to run every time I reload, how can I do that?
You probably have a unique constraint against your id column (or another column in that query) and when you try to add a second row using the same ID it is rejected by MySQL.
You should be doing error checking in your code. You should be checking to see how many rows were affected by your insert (using mysqli_affected_rows()) and, if the number is zero, getting the error message from MySQL (using mysqli_error()).
$result = mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
if (mysqli_affected_rows() === 0) {
echo mysqli_error($con);
}
#DaveChen's comment above is a good solution to your (potential) problem. If it isn't already, make your id column auto increment and then leave it out of your query.
mysqli_query($con,"INSERT INTO 'bird' (`name`, `latin`, `number`) values ('d','cwer','73')");
If your id column is aut_increment and unique: change your code to:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values ('','d','cwer','73')");

MY sql query not working fully

I am using to add data into DB. First i get the values from post and then insert it into table. The problem is that there are total 7 values but only 5 values added and 2 of them not inserted into the table. Here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
$degree_title = $_POST['degree_title'];
$degree_year = $_POST['degree_year'];
$uni_name = $_POST['uni_name'];
$degree_level = $_POST['degree_level'];
$major_sub = $_POST['major_sub'];
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
}
I echo the all values and all values are coming so why they all not inserted into table any idea. Thank
try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, '$eme_uid', '$degree_title', '$degree_year', '$degree_level', '$major_sub', '$uni_name')");
and i would highly recommend:
1) dont use mysql_ its deprecated, use mysqli_*
2) sanitze ALL values in _POST befor using in SQL statements.
if id is autoincrement then you dont need to insert it.
try this
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES ($eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
My guess is that $degree_title and $uni_name doesn't get inserted because they are varchars. In that case you will have to put quotes around these values.
Mysql is kind of "forgiving" in the sence that it does not throw an error when using incorrect types in the sql-statement in relation to the actual type of the column.
Try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, '$degree_title', $degree_year, $degree_level, $major_sub, '$uni_name')");
As mentioned before id doesn't have to be included (if id-column is autoincremental) in the insert-statement, and you should really learn mysqli or PDO.

want to do a double MYSQL INSERT INTO to two different tables

I want to be able to insert into two different mysql tables using php with the second mysql insert being dependent on the member id of the first insert.
For example:
mysql_query("
INSERT INTO `member_users` (
`id`,
`first_name`,
`last_name`,
`username`,
`password`,
`address1`,
`address2`,
`postcode`,
`access`,
`expires`
) VALUES (
NULL,
'$fname',
'$lname',
'$email',
'$passhash',
'$add1',
'$city',
'$postcode',
'',
''
)"
);
Then I want to take the id of this member user to create a mysql_query insert on the same page eg:
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
'$userid',
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
its probably a really easy answer and a really silly question but cannot seem to find the answer anywhere
thanks in advance
If I have understood correctly, and you need to get the member_id from the first query, to use in the second query, you can use the PHP function
$the_member_id = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
You can also do it without using that PHP function
$sql = "SELECT LAST_INSERT_ID()";
// add code here to run the query.
You can use the php function mysql_insert_id() to get the last id you input into the database.
EG:
$sql = "INSERT INTO `table` VALUES (NULL, 'Thomas', 'Male')";
$query = mysql_query($sql);
$id = mysql_insert_id();
So in your question after the first INSERT you need this:
$userid = mysql_insert_id();
Then your second query will work.
You can use mysql_insert_id() to get id, generated by last insert.
mysql_insert_id — Get the ID generated from the previous INSERT operation
You could use the LAST_INSERT_ID MySQL function in your second SQL statement to get the last insert ID from the first.
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
LAST_INSERT_ID(),
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
I would recommend that if you use this approach then you execute the queries within a transaction. That way there's no way that another insert can occur between your first insert and your second, thus throwing off the result of LAST_INSERT_ID.
After executing mysql_query() function you can get lastly inserted id of lastly inserted table by mysql_insert_id().
You can do something like what is done in this example
$sql = "INSERT INTO users(name,gender) VALUES ('$name','$gender')";
$result = mysql_query( $sql,$conn );
$user_id = mysql_insert_id( $conn );
$sql = "INSERT INTO website(site,user) VALUES ('$site',$user_id)";
$result = mysql_query( $sql,$conn );
Manual for mysql_insert_id

Categories