Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm quite new to MySQL, so don't judge! Anyhow, what I'm trying to do is store the 10 newest rows in a MySQL database into a PHP array. My variable $news contains the MySQL data I got from running the fetch_news() query (which I told only to grab content that has a column called type with the value "news" in it). However, I've been unable to do this successfully.
If you guys could offer some help, or guidance, it'd be much appreciated as I have been stuck on on this for quite some time now!
$query = 'SELECT *
FROM `table_name`
WHERE `type`="news"
ORDER BY `article_id` DESC
LIMIT 10';
$query = mysqli_query($link, $query);
$result = array();
while ($row = mysqli_fetch_assoc($query)) {
$result[] = $row;
}
print_r($result);
$newest_ten = array();
$command = "select * from table_name order by date DESC limit 10";
$result = $db->query($command);
while($data = $result->fetch_assoc()){
$newest_ten[] = $data;
}
The command is getting all columns from the table table_name, putting them in order based on their date (so newest to oldest), and then only giving you the first ten of those.
The while loop goes through the results and adds them to an array.
While your "type" column tells you if the row is a news item or not, it doesn't tell you anything about when it was added to the table.
You need to use some other column as well, either some sort of incremental counter (like the "article_id" might be), or a time stamp when the item was added to your table (this is probably the "article_timestamp" in your case).
With one of those you can sort the results the way you want.
When you have sorted your results, you need to limit them to just the 10 you want.
You can find more information about ORDER BY and LIMIT in the Official MySQL documentation.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am attempting to create an autofill info button that retrieves the last inserted information from MySQL and coupled with a $_GET autofills the page with the latest update. I am able to insert and update the data base just fine however upon retrieval of the information my variables remain empty.
I have verified the project-fill button is being posted. I also didnt get any error when checking the query's.
below is a snippet of the section that isnt working. It prints my header but the variables remain empty.
Apologies for sloppy code pretty green.
if(isset($_POST['project-fill'])) {
require "dbh.inc.php";
//select the last inserted row the one with the highest id
$proj1 = mysqli_query($conn, "SELECT * FROM updates WHERE id = MAX");
$proj2 = mysqli_query($conn, "SELECT * FROM updates WHERE id = MAX");
$proj3 = mysqli_query($conn, "SELECT * FROM updates WHERE id = MAX");
//select the column out of that row
$result1 = mysqli_fetch_row($proj1['Project1']);
$result2 = mysqli_fetch_row($proj2['Project2']);
$result3 = mysqli_fetch_row($proj3['Project3']);
//transfer to project variable
$project1 = $result1;
$project2 = $result2;
$project3 = $result3;
//print header to allow for the $_GET method on the project page
header (Location: ../update.php?update=sucessful&p1=".$project1."&p2=".$project2."&p3="$.project3);
}
This is not the correct way to fetch a row from a result:
$result1 = mysqli_fetch_row($proj1['Project1']);
$proj1 is a mysqli_result object, not an array, so you can't subscript it. You need to pass the object to mysqli_fetch_assoc(), and it returns an associative array with an element for each column.
$proj = mysqli_query($conn, "
SELECT Project1, Project2, Project3
FROM updates
ORDER BY id DESC
LIMIT 1");
$row = mysqli_fetch_assoc($proj);
$project1 = $row['Project1'];
$project2 = $row['Project2'];
$project3 = $row['Project3'];
You don't need to query 3 times to fetch different columns from the same row.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a little problem, am trying to read values from mysql table. I have done research and could not find a definite or conclusive answer on this. I will describe the problem:
select data from mysql table using a where e.g where gender=female.
count the results and return the count - just to help know how many records were found
compare a value in table, e.g 'taken' and 'available',
if 'taken' = 'available' in the first record, go to next record(and compare again), if not perform a specific operation in this case can be update or insert or anything of that sort.
the first three are ok and the only problem is, part 4. Kindly help. This is a php problem. Looking forward for your help.
As was said, if you're merely going to skip the record then you may as well not retrieve them in the first place (and thus incur the overhead for having to extract them into PHP memory, etc):
SELECT * FROM `your_table` WHERE `gender` = 'female' AND `taken` = `available`;
However, if you have a specific reason to do this, you can merely do the following:
foreach ($hotels as $hotel) {
// skip if the item is not available, logic can be changed if necessary
if ($hotel->taken >= $hotel->available) continue;
// do the other work here...
}
I interpreted your conditions a little here, assuming you wanted to skip people who aren't 'available'. Though it does look like you wanted the opposite, in which case you can switch the logic in the sql from != to = and in php from != to ==.
Updated: To reflect additional comments made.
Create connection to your database using mysqli or by using PDO.
$db = new PDO($mysqlhost,$username,$password);
$statement = $db->prepare($sqlstatement);
$rows = $statement->execute();
foreach($rows->fetch() as $row)
{
if($row['column_name']==something)
{
//do work
}
else
{
//do work
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have one table which need to find all date and put the name just once (this is workig = $sql), but i have problem to select the that name of data and count how much time is repeats in same table. So where is name Test(down) there needs to be count for how much time that name repeats in whole table.
If I put one more while function the table dies.
Im stacked. Im not very good with php and mysql. If someone can help.
$sql = "SELECT DISTINCT one,two FROM results";
$sql2 = "select test, count(*) as foo_count from results group by test;";
$result = mysqli_query($conn,$sql);
$result2 = mysqli_query($conn,$sql2);
<?php
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["one"]."</td><td>".$row["two"]."</td><td>";}?> Test</td></tr>
I'm having a little bit of a hard time following your question, but I think you are looking for a single sql statement like this
$sql = "select test, count(one) as foo_count from results group by test";
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I wan to load data from mysql with PHP like Facebook (load data by scrolling down). I checked in many tutorial where everyone is doing by order by ID but I can't do so while my fetching query is like follows.
mysql_query("SELECT * FROM conferencecreate WHERE ccFlag = 1 AND ccStartingDate >= '$nowTime' GROUP BY ccTitle");
If I want to implement ORDER BY ccId DESC then its not working. Any Idea how to solve this issue?
I tried this :-
mysql_query("SELECT * FROM conferencecreate
WHERE ccFlag = 1
AND ccStartingDate >= '$nowTime'
GROUP BY ccTitle
ORDER BY ccId DESC");
But this produced the error
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource
You really should not be using the mysql_ database extension any more but that said you need to learn how to process errors generated by any of the the mysql extensions
So try this
$res = mysql_query("SELECT * FROM conferencecreate
WHERE ccFlag = 1
AND ccStartingDate >= '$nowTime'
GROUP BY ccTitle
ORDER BY ccId DESC");
if ( ! $res ) {
echo mysql_error();
exit;
}
Now you should see an error message describing what is wrong with the query you have coded.
Please dont use the mysql_ database extensions, it is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I would like to know how I can search a substring in all columns of a table when I do not know the names of the columns? Is there a foreach-loop-functionallity I do not know?
If I understand you correctly then this may work, brute forces a search through all the results.
Here is a PDO-based example:
$stmt = $dbh->prepare("SELECT * FROM table");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
foreach($row as $column){
if(strpos($column, "find me") !== false)
echo $match."found in:".$column."<br />";;
}
}
I am also lazy. I am also a ColdFusion programmer, not php. However programming logic is the same no matter what the language. I would do this:
Step 1 - Run this query and output the results somewhere
select *
from mytable
where 1 = 2
The outputted results will include the field names. Copy and paste then into your source code as a comment. Delete the ones that you are not going to query. Convert the remaining ones to a list variable. In ColdFusion, that list would look something like this:
listOfFields = "field2,field3,field8,etc";
Fields 1,4,5,6, and 7 were intentionally excluded. We are then going to loop through the list in our query. In ColdFusion, this would be the syntax
<cfquery>
select somefields
from sometables
where 1 = 2
<cfloop list="#listOfFields#" index = "thisField">
or #thisField# = something
</cfloop>
This meets the laziness criteria because you only have to get the field names once. Whether it's better or worse than getting the columns from the system tables and looping through them depends. Doing it this way will make your own app run faster because you don't have to query the system tables every time. However, if a new column is added to your table, you'll have to modify your source code to include it in your search.
If you do decide to query the system tables, make sure you only select char and varchar fields.
Adapt the sample query given at https://stackoverflow.com/a/1054988/1967396
SELECT *
FROM Northwind.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
to get the names of the columns. Then loop over those names to search the table one column at a time for the specific strings. This takes advantage of the efficiency of SQL search and prevents you making a copy of the entire database just to search it (slowly) with nested foreach loops (as in #Silver89's answer).