Returning values from saved row - php

In my PHP code, I save a record like this:-
mysqli_query($con, "INSERT INTO levels (levelName)
VALUES ('" . $_POST["levelName"][0] . "')");
And this works fine.
In the table 'levels', there is an auto-incrementing PK field called "ID". How would I go about returning/echoing the value of that field when the record is saved to the database?

Quoting from the following reference:
How to Get the Unique ID for the Last Inserted Row
If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.
# http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
-
Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "INSERT INTO person VALUES ('Børge','Refsnes','Sandnes','17')";
$result = mysql_query($sql,$con);
echo "ID of last inserted record is: " . mysql_insert_id();
mysql_close($con);
?>
from: http://www.w3schools.com/php/func_mysql_insert_id.asp

use
mysql_insert_id()
function
if using mysqli use something like this
$mysqli->insert_id

Related

Copy value to another table

I have a problem with my code. I have a table called "users" with an "id" field.I want to copy the id value to another table called "aircondition" . This is the code that inserts values into the aircondition table .The problem is that when I use this code I get 0 in the new id field instead of the user.id
<?php
$con=mysqli_connect("localhost","george","george123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
VALUES ('SELECT id
FROM users', '$acname', '$btu', '$space', '$energyclass')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
Use this query
INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users

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...

Return newest row added in MySQL

I was wondering what the code would look like to go into a table and then get the primary key in the last row that was added to the table.
How would you go across doing that I do not have a timestamp in the table for the rows in the database if that helps.
Purely MySQL solution:
SELECT LAST_INSERT_ID();
For PHP with pdo method
$lastId = $con->lastInsertId();
$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());

Data in Mysql Table only store one record

I have mysql data base in which i am adding data in mysql data base but problem is that it only stores only one record not more than that.
my table structure is
<?php
$con = mysql_connect("example.com","name","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("surveyipad", $con);
$response_id=$_POST['response_id'];
$participant_id=$_POST['participant_id'];
$question_id=$_POST['question_id'];
$answer_text=$_POST['answer_text'];
$answer_option=$_POST['answer_option'];
$query=("INSERT INTO survey_question_responses (response_id,participant_id,question_id,answer_text,answer_option)
VALUES ('', '$participant_id','$question_id','$answer_text','$answer_option')");
mysql_query($query,$con);
printf("Records inserted: %d\n", mysql_affected_rows());
echo($response_id)
?>
response id is primary key in table and also set to auto increment
Try like this
$query=("INSERT INTO survey_question_responses (participant_id,question_id,answer_text,answer_option)
VALUES ('$participant_id','$question_id','$answer_text','$answer_option')");
As you made the id field auto incremented don't insert it vie your INSERT query .
Write the query as
INSERT INTO survey_question_responses (participant_id, question_id, answer_text, answer_option)
VALUES ('$participant_id', '$question_id', '$answer_text', '$answer_option')
You should also explain or send the structure of your table.

Accessing last created row in PHP/MySQL

How to access the row which has just been inserted into a DB with PHP/MySQL?
I have:
$sql = 'INSERT INTO `jos_db`.`jos_sections` (`id`, `name`) VALUES (NULL, \'foo\')';
mysql_query($sql, $dbi);
bar();
How do I access the new row in bar()?
If you 'id' column is an auto-increment, you can use mysql_insert_id :
Retrieves the ID generated for an
AUTO_INCREMENT column by the previous
INSERT query.
The example given in the manual looks like this :
$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());
You can get the last item inserted with mysql_insert_id()
http://us.php.net/manual/en/function.mysql-insert-id.php
Use mysql_insert_id() function to select last row inserted in database.
SELECT rows from table where id = last_inserted_id
Using the PHP function mysql_insert_id() will return the id of the last row you inserted.

Categories