PHP: find out the primary key of the just-inserted row data - php

I'm trying to find out the id value which is the primary key of the table. In order to do so, I implemented a code like this.
public function addNewPost($userName, $content) {
// insert post information into the data.
$query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
$result = mysqli_query($this->db->connect(), $query);
$id = mysqli_insert_id($this->db->connect());
if ($result) {
// get the row data with the found primary key
$query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
$result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);
return mysql_fetch_array($result_row_data);
} else {
return false;
}
}
Here I tried to get the id by running thhe $id = mysqli_insert_id($this->db->connect()); command, but it doesn't seem to work.
Any solutions?

You need to use a connection variable not a function call. A second call to connect() is returning a new connection.
$connection = $this->db->connect();
$result = mysqli_query($connection, $query);
$id = mysqli_insert_id($connection);
Or if you keep a variable in the db class which makes sense:
$result = mysqli_query($this->db->connection, $query);
$id = mysqli_insert_id($this->db->connection);

Save the connection
public function addNewPost($userName, $content) {
// insert post information into the data.
$query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
$con = $this->db->connect();
$result = mysqli_query($con, $query);
$id = mysqli_insert_id($con);
if ($result) {
// get the row data with the found primary key
$query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
$result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);
return mysql_fetch_array($result_row_data);
} else {
return false;
}
}

Related

Php sqlsrv_query & sqlsrv_fetch_array used on primary key with Microsoft SQL Server

I am having issues retrieving the primary key from a table.
My table structure is as follows.
In the table is a single record:
id = 1
PlaceName = 'in the matrix'
Retrieved using the following SQL statement directly:
SELECT id
FROM rde_613949.dbo.PlaceNames
WHERE PlaceName = 'in the matrix';
I am attempting to retrieve the id of this record using the following method:
function GetPlaceNameId($locationName)
{
//returns the id of the location name, creating if required
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "SELECT id from rde_613949.dbo.PlaceNames where PlaceName = ?";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$stmt = sqlsrv_query($resource, $tsql, array($locationName), $options);
if ($stmt)
{
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC));
{
$recordFound = true;
$locationId = $row['id'];
return $locationId;
}
}
else
{
return $this -> AddPlaceToDatabase($locationName);
}
}
This method fails at
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
$row returns as null, which means $location also returns as null.
I have another table with another method where this approach works. The only real difference is that I am not returning the primary key in the one that works.
public function FindStudentRecord($studentId)
{
require_once("./Student.php");
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "select FirstName, LastName from rde_613949.dbo.Students where StudentId = ?";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$result = sqlsrv_query($resource, $tsql, array($studentId), $options);
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$student = new Student($studentId, $row['FirstName'], $row['LastName']);
return $student;
}
return null; //no records found return null
}
Please can someone explain the difference in this situation to me and advise me how to do this correctly, please?
While I do not understand why I got around this by selecting * instead of selecting id. If anyone understands this please do a post to advise.

PHP get last insert id in first query and execute it on second query with multi row

I need help. I have a problem using multi query I want to put the last insert id in the next query the problem is it only adds one. Cart_id and qty has a multiple row. Please i need help thanks in advance.
Here is my code:
public function insertOrder($cart_id = null,$qty = null)
{
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = $this->db->con->insert_id;
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Parameters inserting multiple values in each row
if (isset($_POST['cartid']) && $_POST['qty']){
foreach ($_POST["cartid"] AS $key => $item){
$result = $product->insertOrder($_POST['cartid'][$key], $_POST['qty'][$key]);
echo json_encode($result);
}
}
Tried you injecting a sql SELECT query between two insert methods?
public function insertOrder($cart_id = null,$qty = null){
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = getLastId("tablename");
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Get last id function:
function getLastId($tablename){
$sql = "SELECT id FROM $tablename ORDER BY id DESC LIMIT 1";
//any necessary method, and $id = get sql result
return $id;
}

Mysql_result .. not showing data

function getfield($get){
global $connection;
$query = "SELECT id, username, firstname, lastname FROM users WHERE username='".$_SESSION['user_id']."'";
if ($query_r = mysqli_query($connection, $query)) {
$num_rows = ($query_r -> num_rows);
if ($mysqli_result = mysqli_result($query_r, 0, $get)) {
return $mysqli_result;
}
I made a log in form and now all working fine but this function don't showing data. I think mysql_result not working in 7.1.
function getfield($get){
global $connection;
session_start();
$query = "SELECT id, username, firstname, lastname FROM users WHERE username='".$_SESSION['user_id']."'";
if ($query_r = mysqli_query($connection, $query)) {
$num_rows = ($query_r -> num_rows);
if ($mysqli_result = mysqli_fetch_assoc($query_r)) {
return $mysqli_result;
}
}
The function mysqli_result does not exist, so you would need to use something like mysqli_fetch_array(). Replace your innermost if-clause with this:
if ($mysqli_result = mysqli_fetch_array($query_r)) {
return $mysqli_result[$get];
}

How do I modify this MySQL INSERT Query for multiple rows?

I am attempting to insert records for Artists, Songs and Record Labels, whilst checking that the data does not already exist in the Database.
The following code is from Mike Fenwick.
<?php
$query = "SELECT id FROM table WHERE unique1=value1 AND unique2=value2…";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET unique1=value1 AND unique2=value2…";
$insert_result = mysql_query($query);
$id = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$id = $row['id'];
}
return $id;
?>
I need to modify this to check if three unique values exist already (from 3 separate tables), and if not, insert them. Here is my attempt:
<?php
$query = "SELECT id FROM artistsTable WHERE artistName='Beyonce'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET artistName='Beyonce' AND artistImage='beyonce.jpg'";
$insert_result = mysql_query($query);
$artistID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$artistID = $row['artistID'];
}
return $artistID;
$query = "SELECT id FROM recordLabelTable WHERE labelName='Columbia Records'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET labelName='Columbia Records'";
$insert_result = mysql_query($query);
$labelID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$labelID = $row['labelID'];
}
return $labelID;
$query = "SELECT id FROM songTable WHERE trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO songTable SET trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$songID = $row['songID'];
}
return $songID;
?>
I'm assuming that there must be a more efficient way to do this. Any ideas would be much appreciated.
Using basic inset / ignore syntax you could do something like this.
A couple of inserts to put in the artist details and label details, then an INSERT based on a SELECT:-
<?php
$query = "INSERT IGNORE INTO artistTable (artistName, artistImag) VALUES('Beyonce', 'beyonce.jpg')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO labelTable (labelName) VALUES('Columbia Records')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO songTable (trackTitle, artistID, labelID)
SELECT 'Crazy in Love', a.artistID, b.labelID
FROM artistTable a
INNER JOIN labelTable b
ON a.artistName = 'Beyonce'
AND a.artistImag = 'beyonce.jpg'
AND b.labelName = 'Columbia Records'";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
return $songID;
?>
As #LoganWayne says, you probably should use MySQLi .
<?php
/* ESTABLISH CONNECTION */
$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* FOR artistsTable TABLE */
$query = "SELECT id FROM artistsTable WHERE artistName='Beyonce'";
$select_result = mysqli_query($con,$query); /* EXECUTE QUERY */
if (mysqli_num_rows($select_result)==0) { /* IF QUERY'S RESULT IS 0 */
$query = "INSERT INTO table SET artistName='Beyonce' AND artistImage='beyonce.jpg'";
$insert_result = mysqli_query($con,$query); /* EXECUTE INSERT QUERY */
} /* END OF IF */
else {
while($row = mysqli_fetch_array($select_result)){
$artistID = mysqli_real_escape_string($con,$row['artistID']); /* ESCAPE STRING */
} /* END OF WHILE LOOP */
} /* END OF ELSE */
/* FOR recordLabelTable TABLE */
$query = "SELECT id FROM recordLabelTable WHERE labelName='Columbia Records'";
$select_result = mysqli_query($con,$query); /* EXECUTE SELECT QUERY */
if (mysqli_num_rows($select_result)==0) { /* IF QUERY'S RESULT IS 0 */
$query = "INSERT INTO table SET labelName='Columbia Records'";
$insert_result = mysqli_query($con,$query); /* EXECUTE INSERT QUERY */
}
else {
while($row = mysqli_fetch_array($select_result)){
$labelID = mysqli_real_escape_string($con,$row['labelID']); /* ESCAPE STRING */
}
}
/* FOR songtable TABLE */
$query = "SELECT id FROM songTable WHERE trackTitle='Crazy in Love' AND artistID='$artistID' AND labelID='$labelID'";
$select_result = mysqli_query($con,$query); /* EXECUTE SELECT QUERY */
if (mysqli_num_rows($select_result)==0) {
$query = "INSERT INTO songTable SET trackTitle='Crazy in Love' AND artistID='$artistID' AND labelID='$labelID'";
$insert_result = mysqli_query($con,$query); /* EXECUTE QUERY */
} /* END OF IF */
else {
while($row = mysqli_fetch_array($select_result)){
$songID = mysqli_real_escape_string($con,$row['songID']);
} /* END OF WHILE LOOP */
}
?>
SUMMARY:
Used at least MySQLi instead of deprecated MySQL.
Replaced fetch_assoc() function with fetch_array() function.
Used mysqli_real_escape_string() function to prevent some of SQL injections.
Cleaned your code. You have misplaced apostrophes(') and double quotes(") hanging around.

Error when I passed on values on function

Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.

Categories