php/sql need help with query to get last title - php

I have a form where you enter something and it then shows you the id and title of last row, but as its being created there and then it just shows the previous last row at time of submission,
ie if last row id is 23 it would show row 23 when I actually want it to show row 24, to get around this I added +1 to id in the query below:
ie:
$last_id = $lr_result['id'] + 1;
now this works fine for the id but now I'm trying to get the title of the same row but whatever I try I always get the last title (at time of submission),
ie row 23 title rather then row 24 title (or nothing at all in the case for the snippet below).
// fetch id
$lastrow = "SELECT * FROM foo ORDER BY id DESC LIMIT 1";
$lr_result = mysql_fetch_assoc(mysql_query($lastrow));
//fetch id and add 1
$last_id = $lr_result['id'] + 1;
// fetch title where id = last_id
$lasttitlerow = "SELECT * FROM foo WHERE id='{$last_id}'";
$ltr_result = mysql_fetch_assoc(mysql_query($lasttitlerow));
$last_title = $ltr_result['title'];
echo $last_id . $last_title;
As always all help is appreciated and thanks in advance.

SELECT * FROM foo WHERE id = (SELECT max(id) FROM foo)
perhaps? The inner query would return '23', and the outerquery will fetch the entire record. You wouldn't be able to retrieve id=24, because that record doesn't exist yet - you haven't inserted it.

Related

Update query in for loop

why it's not working..
i want to update my table in database this is my code.
for ($i=0; $i <83 ; $i++) {
$link="this is test".$i;
$sql = "UPDATE tbl_gallery_images SET thumbnail_url='$link' WHERE gallery_id=1";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
echo $link."<br>";
}
when i echo that link it's show 100% right but in db just update 82 number in all rows even it is in loop.
thanks in advance.
UPDATE tbl_gallery_images SET thumbnail_url = '$link' WHERE gallery_id = 1
As it is, this query updates column thumbnail_url in all records that have gallery_id = 1. Running the same query 84 times in a loop results in the same set of records being updated again and again in each iteration, with an increasing thumbnail_url. After the last iteration, all records where gallery_id = 1 end up with thumbnail_url = 'this is test83.
A sensible solution would be to add another criteria in the WHERE clause, in order to update just one record per iteration. Assuming that you have some integer column called id to disambiguate the records where gallery_id = 1, you would typically go:
`UPDATE tbl_gallery_images SET thumbnail_url = '$link' WHERE gallery_id = 1 AND id = $i`

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.

How to fetch only 3 data from database table in cyclic order?

I want to fetch only 3 data from database table when any user login.And after that when the next user login the next 3 question will come. How can I do this? What changes should I made in SELECT query?
$sql ="SELECT * FROM questiontypes";
$query = mysql_query($sql);
$qset = "";
while($result = mysql_fetch_array($query)) {
$qset .='<li id="qtypeli">'.$result['qtname'].'</li>';
$sql1 = "select questions .* from questions where qtype='".$result['qtname']."'order by RAND() LIMIT 3";
$query1 = mysql_query($sql1);
while($result1 = mysql_fetch_array($query1)) {
$qset .='<li id="'.$result1['qid'].'" qt="'.$result1['qtid'].'"><span class="qnamespan"> '.$i.'. '.$result1['qname'].'</span></li>
you can set a field in table called taken, in first time the 3 rows taken should be updated with the value 1 in taken field,rest rows will have null in taken. when second time just get the row with max id which has taken=1, increment that id by 1 and get next 3 rows from that id, after getting set the new 3 rows of taken 1 and remove 1 from old 3 rows thats the logic you can apply

show row only 100 times PHP

How can I make a limit of showing the results? I need to limit it for 100 views.
In DB I have:
ID|NAME|PAGE|COUNT|DATE
In count I want to count untill 100 and then stop showing that ID. I could do it with count < 100. And then update the specific ID. I could get records with less than 100 views, but I couldn't manage to update count on the specific ID.
Row is showed with:
php code:
foreach($bannerGroups[0] as $ban) {
echo '<li class="right1">'.$ban->html().'</li>';
}
But I just don't know where to put the update in there. I tried, but all I got was to update only one ID. But it shows 4 on one page and randomizes them on refresh. So I don't know what to do.
Also I would like to say I am only learning php. Sorry for all the mess.
Code at http://pastebin.com/A9hJTPLE
If I understand correctly, you want to show all banners that have been previously-displayed less than 100 times?
If that's right, you can just add that to your WHERE clause:
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' WHERE `COUNT` < 100");
To update them all, you can either run a query while displaying each individual banner, or "record" the id of each and run a single query at the end, like:
$ids = array();
foreach($bannerGroups[0] as $ban) {
$ids[] = $ban['ID']; // record the ID; don't know how Banner
// class works, assuming uses indexes; maybe ID() method?
echo '<li class="right1">'.$ban->html().'</li>';
}
...
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
UPDATE:
Based off of a comment, your Banner class doesn't have a method to retrieve the individual banner's ID. In this case, you can record the ID values when you're building your banners array:
$ids = array();
while($row=mysql_fetch_assoc($bannerResult)) {
$banners[] = new Banner($row);
$ids[] = $row['ID']; // record the ID
}
// update the `count` on each record:
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
sorry, but I got your question wrong...
first you have to insert a new sql-column like "viewcount" to the db...
on every read, you have to increment the value in viewcount...
for that behaviour (because, mysql does not allow sub-selects on update-clause on the same table), you have to fetch the results from db, as you do that, and pass all the primary-keys of the records to an array...
after the view-logic you have to fire up a query like:
UPDATE foo SET viewcount = viewcount + 1 WHERE id IN (1,2,3,4,5,6...,100);
where the IN-clause can be easily generated using your primary-keys-array with "implode(',', $arr);"
hope this helps.
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' AND `count`<100");
#newfurniturey figured it out. in each foreach($banneruGroups added: $ids = $ban->getValue('id'); and then mysql_query("UPDATE dataa SET COUNT = COUNT + 1 WHERE id = '$ids'"); but is there any way to update them by adding query only once? And if the id is showed already 100 times i get Warning: Invalid argument supplied for foreach() in. Any idea how to fix it? I have 4 ids in DB . If one of them already have 100 views (count) then i get error!
Try to limit your data source for 100 items.
It's like OFFSET x LIMIT 100 in MySQL/PostgreSQL query or TOP 100 in MSSQL.

PHP from database and query

I have a table:
id, affiliate
Each time somebody clicks a link, a new row is inserted,
ID being the ID of the page, and affiliate being the ID of the affiliate.
For example:
Page ID: 9 Affiliate ID: 1
Page ID: 9 Affiliate ID: 2
Page ID: 9 Affiliate ID: 3
I only have 3 affiliates.
I want to select this information, and group them by affiliate, for the ID.
I have tried this query:
SELECT COUNT(*) FROM table
WHERE id = '9' GROUP BY
affiliate
It works fine when I do it in php my admin, how do I get the info in PHP?
I have tried:
$q = mysql_query("SELECT COUNT(*) FROM
table WHERE id = '" . $id . "'
GROUP BY affiliate");
$r = mysql_fetch_array($q);
When trying to print the data onto the page, I am only getting one result.
Do I need to use a foreach/while loop to get all 3? How would I go about doing this?
Thank you!
You should do mysql_fetch_array() (or mysql_fetch_assoc()) in a loop:
while ($row = mysql_fetch_assoc($q)) {
echo $row["id"];
echo $row["affiliate"];
}
UPDATE (in accordance with comment):
If you ALWAYS have 3 rows in your result, probably mysql_result() function would be helpful:
$firstAffiliate = mysql_result($q, 0, "affiliate");
$secondAffiliate = mysql_result($q, 1, "affiliate");
$thirdAffiliate = mysql_result($q, 2, "affiliate");
BTW, be careful and check, whether query actually returns 3 results.
Loop like this:
while($row = mysql_fetch_array($q)) {
print_r($row);
}
If you just want to get list of Affiliate ID, you can consider this query
select group_concat(affiliate)
from table
where id=9;
The above will return a comma separate value like 1,2,3 in single row
So, you can then in PHP explode using ,, and the size of the exploded array is the same as count(*)
you can use a variable to hold state inside the actual mysql statement itself. Try the following:
affiliates:
page_id
afil_id
set #page_id=0;
select page_id, if(#page_id <> page_id, count(*), 0), #page_id:=page_id from clicks group by page_id;
Hope that helps

Categories