php update record based on fetch - php

[UPDATE: found solution. see my own answer, below]
i'm trying to learn php and i can't figure how to do something that seems extremely basic, i.e. update a record based on fetching criteria. here's the part of my code that successfully fetches the record:
mysql_select_db('top_choice_system');
$query = "SELECT item_name FROM main ORDER BY cw DESC LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "-- item name --" . $row['item_name'];
how do i update the specifically fetched item?
ftr below is the code i successfully use to update a record. however, in the code below, i specify the record myself in the WHERE portion:
$sql = 'UPDATE main
SET column5=28
WHERE ITEM=15';
my point is i can't figure how to make the WHERE match the fetched record. (or, better yet, how to fetch AND update with the simplest, shortest method.) thank you in advance for any help.
rephrasing my question: i'm learning several things from online tutorials, but for some reason i can't find the most basic info about updating a record but NOT based the record's id: for example, you want to update the specific record that matches a specific criteria. (as in the example above, wanting to update whichever record will be at the top of a specific column if that specific column is ordered from top to bottom.)

update main set column5 =
(SELECT item_name FROM main ORDER BY CW DESC)
you can use query like this update and select together your question is not cleared what data you want and which data you want to update so you can search about update select query and make your query as per your requirement....

EUREKA:
$sql = 'UPDATE main
SET testfield="YES" ORDER BY columnX DESC LIMIT 1';
note:the ORDER BY condition did not work with a WHERE line. it worked when i added it to the SET line.
(ftr found code on http://www.phpknowhow.com/mysql/update-statement/)

Related

Needing only 1 row from PHP MySQL database

I'm sure I've done this in the past, but it's a few years ago and I don't remember how it's done and the online tutorials aren't helping.
I have a MySQL database. It has 1 table in it called 'data'. In the 'data' table, there are about 15,000 rows, and 31 columns. I need to extract the data from only 1 of these rows, based on a lookup referencing the string in column 1. When the mysql query finds the correct row, I need every single item read into variables that I can show on my page.
I believe this line is the problem:
$sql = "SELECT Mark,Manufacturer,Model FROM data";
Could someone please let me know what it needs to be changed to, to get the desired result? TIA! :)
you can set options of select query
$sql = "SELECT Mark,Manufacturer,Model FROM data WHERE Model (or manufacturer,mark) = 'some text'";
As my colleges have Explained "where' is your friend!
So you can always query as follows :
Select * from Data
Where column_1 = 'Your Desired String'
Alternatively you could use
Select Discinct Limit 1 Mark,Manufacturer,Model FROM data
Order By Mark Asc

What is the difference between while and between, and what is the better choice in my case?

I have a table that have hundreds of rows, and i want to get specific rows, I used the LIMIT and between id and id
In my application i have two text inputs, one is for START NUMBER and one is for END NUMBER, When i use the LIMIT i need to tell the user to make the right calculation to get the right start and end
So for example if i have a table of 3000 rows, and i want to select 100 rows above 2000 the query will be :
Select * from table LIMIT 2000,100
This will select 100 rows above 2000
The between method :
In the between method, i'm running a while function on all the table and i'm using IF statement to get the right id's here is what i'm doing :
Select * from table
$datastart = $_POST["datastart"];
$dataend = $_POST["dataend"];
$firstid = 0;
$lastid = 0;
$varcount6=1;
$sql = "select ID from users_info";
$sqlread = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($sqlread)){
if($datastart==$varcount6){
$firstid = $rowdirstid["ID"];
}
if($varcount6>=$dataend){
$lastid = $rowdirstid["id1"];
break;
}
$varcount6++;
}
So now i have the first id and the last id of the table, next i use another sql query :
Select * from table where id between $firstid and $lastid
Both worked
My question is: what should i use if i'm loading huge amount of data each time ?
Should i go with while ? or the LIMIT will make the job done ?
To begin with, you should never use PHP to get the data required, stick to doing that solely in SQL, as PHP is never needed.
The limit query you're using will not cut it for what you're trying to do, as it will not care what id's the entries has, so, if your id's are not 100% consecutive, you will not get the desired result.
You should use the between query you display at the bottom of your post.
But, since you haven't provided your full code I cannot say wether or not you sanitized that input, but that is always a good thing to keep in mind. It's preferable to use parameterized queries instead aswell.
If your sure the ID are consecutive, use SELECT * FROM t WHERE id BETWEEN a AND b ORDER BY ID ASC
If you use LIMIT, the SQL Engine have to scan and order all the first results.
(and index the id field)

MySQL PHP Grabbing rows not relevant to query

I have no clue what I could be doing wrong. This has only ever happened with the Change logs that I've been trying to develop. I coded this from scratch, and it really couldn't be much simpler.
For some reason when I try to grab rows that are only
is_dev='1' (Is in development)
OR
planned='1' (Is planned)
AND
website_id='13' (ID of website)
It shows a result from another website ID ("9").
This is my current query:
**$getdev = mysql_query("SELECT * FROM changelog_entries WHERE in_dev='1' OR planned='1' AND website_id='13' ORDER BY id DESC");**
This is what I get in return, I wrote on the picture what website id they belong to.
https://img.rnjrweb.com/errorchangelogs.PNG
I've also tried this query:
**$getdev = mysql_query("SELECT * FROM changelog_entries WHERE website_id='13' AND in_dev='1' OR planned='1' ORDER BY id DESC");**
and when I do, it returns even more irrelevant rows.
Any clues? I'm pretty stuck here. Thank you!
You need parenthesis around your OR:
SELECT * FROM changelog_entries WHERE (in_dev='1' OR planned='1') AND website_id='13' ORDER BY id DESC
If you don't put them any website_id row having in_dev=1 will match.

MySQL remember last position

I have made a small app where a table of data is presented to the user. The data can be sorted by different column headers and filter using inputs.
When the user clicks on a row it opens a small popup which contains two arrows for going to the next and previous record, in the same order as they appear in the table.
Originally I had (for "previous" as an e.g.):
SELECT ed.id
FROM entity_details AS ed, users
WHERE ed.id > ?
AND ed.typeRef = ?
AND ed.ownerRef = users.id
$filter
$SQLOrder LIMIT 1
Which works fine if the table is sorted by ed.id, but will not work properly if sorted by another column e.g. ed.name, because the next alphabetical name might have a much higher or lower id.
FYI $filter could be something like:
AND branchRef = 2
and $SQLOrder could be:
ORDER BY ed.name DESC
What do I need to do to make it cycle through the records properly, respecting current order and record position?
All the sorting and filtering parameters come through over AJAX, e.g:
$JSON->selectedbranch ;
I've come to the conclusion that all I need to know is how to start the query from a row with column X containing value Y, is that possible?
You should store the number of the row you displayed, not the ID. Then just do the ordering in SQL as your application requirements imply, then apply the knowledge contained here:
Skipping first n results in MySQL
To simplify the job, and to make this answer usable for future SO dwellers:
SELECT ed.id
FROM entity_details AS ed, users
WHERE ed.typeRef = ?
AND ed.ownerRef = users.id
$filter
$SQLOrder
LIMIT $currentRowNum,1
This scheme smells however: using this to navigate your rows implies a SQL query for each navigation action. That might have an bad effect on your response time...
PHP's mysql_data_seek function may helps.
mysql_data_seek
I found it, seeing that other guys answer gave me an idea, but his answer has disappeared :(
For the next button I have:
$result = $dbh->prepare("SELECT ed.id
FROM entity_details AS ed, users
WHERE $WHERE < ?
AND ed.typeRef = ?
AND ed.ownerRef = users.id
$filter
ORDER BY ed.name DESC LIMIT 1") ;
$WHERE is just the column name "ed.name".
I just have to sort out the dynamics for $where and the ORDER BY clause and it'll be good to go.
Thanks for every ones input!

Order By DESC/ASC not working within PHP Query

I have this code so far which is within 2 while loops:
mysql_query("SELECT * FROM listing WHERE
(category_id='$category' OR category_id_2='$category' OR category_id_3='$category')
AND listing_status='1' AND listing_type='1' AND listing_id='$listing_id'
ORDER BY overall DESC");
The data is showing exactly what I want, however the ORDER BY simply isn't working. I'm not too sure what it's ordering by. The overall column itself is DECIMAL(12,2).
The values are saved to only 2 decimal places. For instance, in each row it could be 2.56, 2.89. In this case I want the 2.89 to show before the 2.56. However, it's not.
Many thanks in advance.
I believe you are only selecting one element at a time in your query, something like
while(...){
$category = ...;
$listing_id = ...;
// Your query which only returns one result here
}
Then since your query only returns one result it has nothing to sort, and you see the results in the order the queries are executed.
You need to rewrite your query to select all the rows you want in one go instead of having it in a loop if you want ORDER BY to work. Using IN in your query may help you.
Have you tried casting the field as a decimal in the order by?
ORDER BY CAST(overall as DECIMAL) DESC
I have managed to solve the problem.
By implementing the 'overall' column in the first loops table, instead of the second. It orders the data first by overall, and then goes ahead and gathers the other data from the second table.
Many thanks for your help.
Try:
mysql_query("SELECT * FROM listing WHERE
(category_id='$category' OR category_id_2='$category' OR category_id_3='$category')
AND listing_status='1' AND listing_type='1' AND listing_id='$listing_id'
ORDER BY overall+0 DESC");
The query is fine. The problem is probably with how you iterate returned data. Try changing it.
If not, provide us with the whole relevant piece of your PHP code.
I don't know why, but I found out by copying and pasting from phpmyadmin that this worked to solve a similar problem. The ' is changed to ` - dunno if it's important. But definitely ASC worked with the second way.
Important - the have been stripped from the second method, put them around the table name and the column names.
instead of
$sql = "SELECT * FROM 'dczcats' ORDER BY 'first' , 'second' ASC";
I typed this
$sql = "SELECT * FROM `dczcats` ORDER BY `dczcats`.`first` , `dczcats`.`second` ASC";

Categories