How To select last inserted Row in PHP , Mysql - php

I m trying to create ID like "A1 , A2, A3 .. etc
So i tried like this
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
if($count2>0)
{
$merge_id5 = explode("A",$merge_id5);
$mergeid_no = $merge_id5[1]+1;
$merge_id6 = $mergeid_no;
}
else
{
$merge_id6 ="1";
}
if($count<1)
{
$merge_id = $merge_id5;
}
Everything is working fine... but after creating A9, it create A10 then again it creates A10 not moving to A11 , A12 . etc., i think if i write correct query to fetch last inserted row i'll fix this issue
Please someone help me
db table :
merge_id | name |
A1 | xxxx |
A2 | yyyy |
A3 | zzzz |
....
....
A9 | sds |
A10 | dsfs |

i know it is not the best solution to your problem, but this will help you.
and just get the first record because if i add LIMIT 1 the output is wrong :(
SELECT * FROM merge_info ORDER BY LENGTH(merge_id) DESC

Change your query to:-
SELECT MAX(merge_id) FROM merge_info;

I think it's better you use an auto_increment field, to get the last insert row with LAST_INSERT_ID(), otherwise you can't be sure if the last row, the one you have inserted.
So long. To order with your solution, use this.
ORDER BY SUBSTRING(merge_id,2) DESC

Better approach to your problem could be ,
use AUTO_INCREMENT field and while displaying append 'A' to it.
Now to solve this you can use below SQL statement
SELECT * FROM `merge_info` ORDER BY SUBSTRING(merge_id,2) DESC limit 1

should change you merge_id column into auto increment column,and the change your query into below mentioned,
SELECT MAX(merge_id) FROM merge_info;
if you want id like A1,A2,A3 ... then you can use the below code for get it
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
$merge_id="A".$merge_id5;
after above process,noe we have a meger_id like A1,A2.. on application side

Related

while() in while() or 1x Query?

I don't know which way would be better for PHP and SQL.
I design and program my own comment system and I would like id2=0 its a comment and id2>0 its sub-comment in one table. This means that if someone wrote a sub-comment in a comment with ID=1, then ID2 is responsible for assigning (sub-comment) to ID=1 (comment).
I have one table comments like this:
id | id2 | smt | etc.
1 | 0 | x | x //comment with sub-comment where id=3
2 | 0 | x | x //comment
3 | 1 | x | x //that is sub-comment for comment where id=1
I'm displaying this in a while loop because I need to print all the data from comments. Like this:
$sqlkom="SELECT * FROM `comments` WHERE `id`='".$row['id']."' ORDER BY id DESC LIMIT 20";
if($resultkom = mysqli_query($con, $sqlkom)){
if(mysqli_num_rows($resultkom)){
while($rowkom = mysqli_fetch_assoc($resultkom)) {
echo HtmlFormatFunction($rowkom['id'],$rowkom['id2'],$rowkom['smt'],$rowkom['etc'])
I won't achieve this: if($rowkom['id']==$rowkom['id2']) without adding another while() loop, right?
or maybe it is enough to modify the SQL query to achieve this effect? Please, help me with the right solution.
You can join your table with itself, something like that:
SELECT c.id, c.id2, c.smt, c.etc,
s.id, AS s_id, s.id2 AS s_id2, s.smt AS s_smt, s.etc AS s_etc
FROM `comments` c LEFT JOIN `comments` s
ON c.id = s.id2
WHERE c.id = ?
ORDER BY c.id DESC LIMIT 20";
Then you should get minimum one line for the first comment or as much as lines for the first comment as there are sub-comments. Then the first four fields will repeat, but thats not an issue. Maybe this is not perfect. Hope you get the idea.

PHP remove specific numbers from MySQL field

My db is structured like:
id | posts | groups
----+--------+-----------
1 | 10 | 2
2 | 30 | 2
3 | 20 | 2
4 | 50 | 2,8
5 | 54 | 2,8
When a user gets to 50 or more posts I want the script to remove the group '2'. There is already a prior script that adds the '8'.
I have this:
$cusstring = mysql_query("SELECT `groups` FROM `users` WHERE `postnum` >= 50 ");
$row = mysql_fetch_array($cusstring);
$array = explode(',', $row[groups]);
$pos = array_search('2', $array);
unset($array[$pos]);
$row[groups] = implode(',', $array);
mysql_query("UPDATE `users` SET `groups` = $row[groups] WHERE `postnum` >= 50 ");
It just doesn't seem to update though. I don't know if this is because it picks up multiple fields in the array or if I'm doing something wrong with the greater than or equal to symbol.
Can anyone offer a solution?
Thanks.
EDIT:
I've worked out that if I change the symbol to equal to the query works on the first row it comes across with a post count of 50 but it leaves the rest. It would appear it's only able to process one row.
I think this would work for you. I think a SQL approach would be more efficient but you've said you want to keep it in PHP.
$cusstring = mysql_query("SELECT `groups`, `id ` FROM `users` WHERE `postnum` >= 50 ");
while($row = mysql_fetch_array($cusstring)) {
$groups = mysql_real_escape_string(preg_replace('~(^|\s+)2(,|$)~', '', $row['groups']));
//regex demo https://regex101.com/r/eX7qD1/1
$id = (int)$row['id'];
mysql_query("UPDATE `users` SET `groups` = '$groups' WHERE `id ` = $id ");
}
Your code is only getting one record because you aren't looping the fetch.
Also don't put data that comes from your DB back into a query directly this can lead to a SQL injection. Note I cast the ID here to an int and escaped the groups value. This should prevent the possibility of an injection.
You should switch drivers to PDO or MYSQLI. Once using one of those drivers you can use prepared statements.
This solution also will put an empty value in the groups field if 2 was the only value.

How to get the next row in sql

I have a table that is something like this
id | names | value
1 Vicky 43
2 Erica 23
3 Rueben 33
4 Bob 54
5 Chris 60
Then I set them in order according to their value. Now the table looks like this.
id | names | value
5 Chris 60
4 Bob 54
1 Vicky 43
3 Rueben 33
2 Erica 23
Now the starting point is id 5 which has a name of Chris and a value of 60. My goal is, to get the next row which has an id of 4 and name of Bob and a value of 54.
You just need to limit the resultset:
SELECT * from table
ORDER BY value DESC
LIMIT 1, 1
Output:
| ID | NAMES | VALUE |
|----|-------|-------|
| 4 | Bob | 54 |
Fiddle here.
The LIMIT basically works this way: the first number sets the starting point (being 0 the minimal value) and the second number the amount of items to fetch (in this case only one).
Edit:
A different way of understanding the question would be: Given a value for a particular field (EG: id field with value of 5)... what would be the previous record? As we have the id 4 in the data we should return that one.
That could be accomplished this way:
SELECT * from t
WHERE id < 5
ORDER BY id DESC
LIMIT 1
Fiddle here.
This way you can traverse the results in both orders (ASC and DESC) and also get both the next or previous (> or <) rows.
If your current ID is for example 4 then
Next:
select * from foo where id = (select min(id) from foo where id > 4)
previous:
select * from foo where id = (select max(id) from foo where id < 4)
sql server:
with temp as
(
SELECT ROW_NUMBER() OVER (ORDER BY value desc) AS ROWID, * FROM table_name
)
SELECT * from temp where ROWID=2
mysql:
SELECT * from table
ORDER BY value DESC
LIMIT 1, 1
I get the feeling that this is a PHP related question?
If that's so, then you can use PHP's mysql or mysqli_fetch functions to get what you want... along with a loop
This is your basic loop-through-a-mysql-query
$sql = mysql_query( "SELECT * from table ORDER BY value DESC" );
while ( $r = mysql_fetch_array( $sql ) ) {
echo $r['value'] . "<br />\n";
}
If you want to have them all at your disposal and be able to call either one of them at will, you will need to store the data in an accessible array, like so
$sql = mysql_query( "SELECT * from table ORDER BY value DESC" );
$theData = array();
while ( $r = mysql_fetch_array( $sql ) ) {
$theData[] = $r['value'];
}
Then, to access the SECOND value, use this
echo $theData[1];

Using OR and AND in MySQL

I have a query as follow: (shows are a table with tv shows and IMDB ID and recommended_titles is a table with two columns with IMDB_ID)
Select t2.* from shows t, shows t2, recommended_titles WHERE
t.imdb_id = recommended_titles. title_id_1
AND recommended_titles.title_id_2=t2.imdb_id
AND t.imdb_id = 0367279 LIMIT 7
The query is fine but I realized that it was only checking in the first column for my imdb id when it can also appear in my second one.
So i try to add the following:
OR
recommended_titles.title_id_2=t.imdb_id
AND t.imdb_id = recommended_titles. title_id_1
AND t.imdb_id = 0367279 LIMIT 7
But apparently OR can't be used with AND,
any suggestions as how I should do this ?
Edit:
To explain what I'm trying to do, here's a quick example in case my explanations above are too confusing.
table shows has rows like this:
name of a tv show | 00001
name of another | 00002
name of another | 00003
table recommended titles has (notice that an ID can be in either column)
00001 | 00002
00002 | 00003
You may look at operator precedence in mysql (and see that AND has an higher precedence than OR), or use parenthesis (much easier to use and maintain)
(t.imdb_id = recommended_titles.title_id_1 OR
recommended_titles.title_id_2=t.imdb_id)
AND recommended_titles.title_id_2=t2.imdb_id
AND t.imdb_id = 0367279 LIMIT 7
Do it like this,
(recommended_titles.title_id_2=t.imdb_id
OR t.imdb_id = recommended_titles. title_id_1)
AND t.imdb_id = 0367279 LIMIT 7
(t.imdb_id = recommended_titles. title_id_1
OR recommended_titles.title_id_2=t.imdb_id )
AND t.imdb_id = 0367279 LIMIT 7
Just use parenthesis to group your conditions for priorities.

Combine two word from a MySQL database at random

I have a database with nouns and adjectives for example:
id | type | word
-----------------------
1 | noun | apple
2 | noun | ball
3 | adj | clammy
4 | noun | keyboard
5 | adj | bloody
ect...
I want to create one query what will grab 10 random adjectives and 10 random nouns and put them together.
Having trouble doing it, is this possible?
Thank you!
You can get 10 random elements per type with queries like this:
select word from YOUR_TABLE where type = 'noun' order by rand() limit 10;
select word from YOUR_TABLE where type = 'adj' order by rand() limit 10;
and then put them together in your PHP code, like so:
$phrases = array();
$adj_result = mysql_query("SELECT word FROM words WHERE type = 'adj' ORDER BY RAND() LIMIT 10");
$noun_result = mysql_query("SELECT word FROM words WHERE type = 'noun' ORDER BY RAND() LIMIT 10");
while($adj_row = mysql_fetch_assoc($adj_result)) {
$noun_row = mysql_fetch_assoc($noun_result);
$phrases[$adj_row['word']] = $noun_row['word'];
}
print_r($phrases);
Please note that this code is not very safe (it makes the assumption that the second query always yields as least as many results as the first), but you get the idea.
Edit: Here's a single SQL query that should do it:
select t1.word, t2.word
from
((select word from YOURTABLE where type = 'adj' order by rand()) as t1),
((select word from YOURTABLE where type = 'noun' order by rand()) as t2)
order by rand()
limit 10;
EDIT: removed example

Categories