Use mysql_insert_id in single query - php

Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this

From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.

It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value

I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.

Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`

Related

How to store a PHP variable from a SQL table INT camp

This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}

Check which columns were modified in an UPDATE query

When we update a MySQL record with php, we can check if it has effect using:
$mysqli->affected_rows;
But how do I check which column has been modified?
Example, in my table have the columns: id / name / age
In a record we have the data: 1 / Woton / 18
If I send an: UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'
Only the age field has changed. How can I determine this?
You cannot directly get the updated columns from the query result.
It can be get from some php query. Firstly we will have to select the row from database which we are going to update in a array variable. Than run the update query for the same row.
Lastly get the same row from database from select query in the new array variable.
Finally we get two arrays.
We can get the updated column with the array_diff_assoc php function.
See the below code for the same.
$sql = "SELECT * from mytable where id=1 limit 1";
$prev = mysqli_fetch_assoc(mysqli_query($conn, $sql));
//Get the column data in the array. Before update.
$sql = "UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'";
$conn->query($sql);
// Update data
$sql = "SELECT * from mytable where id=1 limit 1";
$updated = mysqli_fetch_assoc(mysqli_query($conn, $sql));
// Again run the select command to get updated data.
$UpdatedColumns=array_diff_assoc($updated,$prev);
In a different note: If QueryLog has been enabled in the DB then you (or your script in PHP or Python or any) can easily see/read which part of the content has been updated and even you can monitor the DB.
The good news is, even you can target which table, which query etc.

PHP loop through array to update SQL database

I am trying to loop through an array ($lineup_selected) that corresponds to a player row in a database. For each player I would like to execute an UPDATE query to the database that adds the value of $submissions_selected to the total_picks column. I am struggling with the code as it fails to execute the query. Any help please?!
// Select team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
// Loop through and update total_picks for each player in database present in lineup_selected array
$player_picks_query = "SELECT full_name, total_picks FROM table WHERE team=$team_selected";
$result = mysqli_query($conn, $player_picks_query);
while($row = mysqli_fetch_assoc($result)) {
$player = mysql_real_escape_string($row["full_name"]);
$add_player_picks = "UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name = '$player'";
}
why not:
UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE team = '$team_selected'
this way you have only one query to execute and let your database do the looping. Else you would first select some records and then have your database update each one of them to update the record.
I assume the fullname is unique. If not, it would mean your version can have the update-query modify multiple records each time and so my approach is invalid
-- and I seem to repeat a lot of the comments when stating to sanitize and escape your input to be save(r).
edit:
combined it should come to:
// set team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
$updatequery = "UPDATE table
SET total_picks = total_picks + ?
WHERE team= ?";
$stmt = mysqli_prepare($updatequery);
mysqli_stmt_bind_param($stmt, "is", $submissions_selected, $team_selected);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
Myself I am more into the pdo approach, but syntax should be like this.
In your select request you have a team that is obviously a String. So, maybe you can try your request like : "SELECT full_name, total_picks FROM table WHERE team='$team_selected'"
I don't know if PHP is smart enough to put the quotes.
I think it will be better if you use only an update statement.
First of all you implode your array
$lineup_selected = array("player1", "player2", "player3");
$players='".implode("','",$lineup_selected )."';
Now you can update the table
$updateStmt="UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name in (".$players.") and team=".$team_selected.";

Delete from sql statement

I have a script which is supposed to delete a post from a database, however when the query is executed it does not delete anything. This is the query string.
$query = "DELETE post FROM kaoscraft_posts WHERE post_id = $postid"
What is wrong with the statement?
Yes, all variables are set and yes I have tested with an exact post_id
If you need more information, please just comment and tell me, don't be rude about it.
From the MySQL manual:
For the single-table syntax, the DELETE statement deletes rows from tbl_name and returns a count of the number of deleted rows.
So you can't delete the post only, you need to delete whole row.
$query = "DELETE FROM kaoscraft_posts WHERE post_id = $postid"
If you want to clear the post only, you can do it by UPDATE statement.
Delete query structure should be like this:
DELETE FROM table_name WHERE condition ;
You can not delete a column value in your table. you need to delete whole record of a row. If you wanted to delete single row then you need to update this row.
try this:
$query = "DELETE FROM kaoscraft_posts WHERE post_id = $postid";
You have an extra 'word' in your statement... it should be
$query = "DELETE FROM kaoscraft_posts WHERE post_id = $postid"
Please look on the below syntax,you come to know your mistake
DELETE FROM table_name WHERE column_name = some_value;

Can't access row with 'fieldName' using MAX() in PHP MYSQL

I have small PHP script which has
$query = "SELECT MAX(id) FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row[0];
Which runs fine, but I want to understand why i can't access the row with the fieldname, like if i have this
$query = "SELECT id FROM `dbs`";
i am able to use the folowing
$val = $row['id'];
but whenever i use this MAX() function, i have to change to
$val = $row[0];
to access the values
I have no clue about this. Any help would be appreciated. Thankss
You need to give it an alias:
<?php
$query = "SELECT MAX(id) AS `id` FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row['id'];
Edit:
To explain this it's probably best to show an example of a different query:
SELECT MAX(`id`) AS `maxId`, `id` FROM `dbs`
Using the above it will return as many rows are in the table, with 2 columns - id and maxId (although maxId will be the same in each row due to the nature of the function).
Without giving it an alias MYSQL doesn't know what to call it, so it won't have an associative name given to it when you return the results.
Hope that helps to explain it.
SELECT MAX(id) AS myFieldNameForMaxValue
FROM `dbs`
and then
$row = mysql_fetch_array($result);
$val = $row['myFieldNameForMaxValue'];
If you run this query on mysql commandline you'll see that the field name returned by mysql is MAX(id). Try running on phpmyadmin and you'll see the same. So if you try $row['MAX(id)'] it'll work. When using a mysql function, it gets added to the name, so use an alias, like other said here, and you're good to go: SELECT MAX(id) AS id FROM dbs. Also, never forget to use the ` chars, just in case you have some columns/tables with reserved names, likefrom`.

Categories