So what I want to do is I want to search for a certain name in a column called 'filename' and display the 'count' on that row.
This might help explain:
I want to search for Packages in the 'filename' column but I want to display the 'count' on it (4)
id filename count
1 Packages 4
2 Another 7
$filename = 'Packages';
$result = mysql_query("SELECT `count` FROM `downloads` WHERE `filename` = $filename");
Also note that if the filename can come from user input you have to be aware of injection attacks.
$filename = 'Packages'; // From user
$filename = mysql_real_escape_string($filename);
$result = mysql_query("SELECT `count` FROM `downloads` WHERE `filename` = $filename");
Here is an example that selects all Filenames and counts and lists them in a table:
$result = mysql_query("SELECT `filename` `count` FROM `downloads`");
?><table><tr><td>Filename</td><td>Count</td></tr><?php
while($row = mysql_fetch_assoc($result)){
?>
<tr><td><?php echo $row['filename']; ?></td><td><?php echo $row['count']; ?></td></tr>
<?php
}
?></table><?php
Assuming what you actually wants is a report of download counts for each filename, you need to use the GROUP BY clause in your SQL statement:
<?php
$res = mysql_query('SELECT id, filename, COUNT(*) AS count FROM downloads GROUP BY filename');
if (is_resource($res)) {
while (false !== ($row = mysql_fetch_assoc($res))) {
printf('%d - %s - %d', $row['id'], $row['filename'], $row['count']);
}
}
?>
$query = "SELECT count FROM downloads WHERE filename='Packages'";
EDIT:
$result = mysql_query($query, $con) or die(mysql_error());
$arr_down = mysql_fetch_assoc($result);
echo $arr_down["count"];
UPDATE: For one or more rows with 'Packages' in it, you can show the results in a table like this:
$con = mysql_connect("localhost", "MySQL_username", "MySQL_password") or die ("Unable to connect to MySQL Server " . mysql_error());
$fname = "Packages";
$query = "SELECT filename, count FROM downloads WHERE filename='" . $fname . "'";
$result = mysql_query($query, $con) or die(mysql_error());
$html = "<table>\n<tr><th>Filename</th><th>Count</th></tr>\n";
while ($row = mysql_fetch_assoc($result))
$html .= "<tr><td>" . $row['filename'] . "</td><td>" . $row['count'] . "</td></tr>\n";
$html .= "</table>\n";
echo $html;
$count = mysql_num_rows($result)
echo($count)
Check out the PHP mysql documentation for more. In particular you'll want to learn about the fetch() functions, which you'll use to display the data you retrieve with your query.
the raw query would be:
select count( filename ) from downloads;
Edit: Okay, you want to loop them onto the page:
foreach( $result as $i )
{
if( !empty( $i ) )
{
echo "<div>$i['column_name']</div>";
}
}
Related
Some of my rows have a "," comma as the initial character in the field. So I need to loop through, check if each row has the initial commma, remove it if it does, and update the row.
I am running the following code, which seems to go on an endless loop when the update is called.
When I am just echoing out the result at the end, everything looks fine in the browser. But on execution of the update line below the echo, it seems as if a single datum from the column "Tags" is being populated for every record, instead of just the rows that have the initial commma that I am removing.
Would love help :)
$query = mysql_query("SELECT Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query))
{
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial = ",") {
$str = (ltrim($str, ','));
}
echo "result: " .$str . "<br/>";
$result = "UPDATE products SET Tags = '" .$str ."'";
mysql_query($result);
}
Thank you.
You should pass the particular row id to the one you're making changes to, by using a WHERE clause:
$query = mysql_query("SELECT Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial == ",") {
// == not =
$str = (ltrim($str, ','));
}
$id = $row['id'];
echo "result: " .$str . "<br/>";
$result = "UPDATE products SET Tags = '$str' WHERE id = $id";
mysql_query($result);
}
By the way, if possible kindly change to the better extension which is mysqli or PDO instead.
You're if() statement has an error in it.
You're using one equal:
if($initial = ",") {
}
Instead of two for actual comparison:
if($initial == ",") {
}
Here is the complete code. Thank you everyone.
$query = mysql_query("SELECT ProductID, Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial == ",") {
$str = (ltrim($str, ','));
$id = $row['ProductID'];
//echo $id . " ";
//echo $str . "<br/>";
$result = "UPDATE products SET Tags = '$str' WHERE ProductID = $id";
echo $result ."<br>";
mysql_query($result);
}
}
So grateful for the help. I will update to mysqlli also.
I have two tables, posts and sections. I want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places. I make a function:
function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
$maxpost12 =mysql_query($maxpost1);
while ($maxpost_rows = mysql_fetch_array($maxpost12 ,MYSQL_BOTH)){
$maxpost2 = $maxpost_rows[0];
}
$query = "SELECT * FROM posts WHERE id = $maxpost2";
$query2 = mysql_query($query);
return $query2;
}
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){
echo $rows['title'] . "<br/>" . "<br/>";
echo $rows['id'] . "<br/>" . "<br/>";
echo $rows['image_section'] . "<br/>";
echo $rows['subject'] . "<br/>";
echo $rows['image_post'] . "<br/>";
}
How can it take these ten results but use them in different places, and keep them arranged from one to ten.
this was the old case and i solve it but i found another problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.
function getmax_id_with_minus ($minus){
mysql_set_charset('utf8');
$maxid ="SELECT max(id) FROM posts";
$maxid1 =mysql_query($maxid);
while ($maxid_row = mysql_fetch_array($maxid1)){
$maxid_id = $maxid_row['0'];
$maxid_minus = $maxid_id - $minus;
}
$selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
$query_selectedpost =mysql_query($selectedpost1);
return ($query_selectedpost);
}
<?php
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>
anyway "really" thanks again :) !
A few thoughts regarding posted code:
First and foremost, you should stop using mysql_ functions as they are being deprecated and are vulnerable to SQL injection.
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
When you SELECT MAX, MIN, COUNT, AVG ... functions that only return a single row, you do not need an ORDER BY or a LIMIT.
Given that you are only asking for the MAX(id), you can save work by combining your queries like so:
SELECT * FROM posts
WHERE id = (SELECT MAX(id) from posts WHERE section_id = $section_id)
If I'm understanding what you're trying to do (please correct me if I'm wrong), your function would look something like:
function sectionposts($section_id) {
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$stmt = mysqli_prepare($link, "SELECT title, id, image_section, subject, image_post FROM posts "
. "WHERE section_id = ? ORDER BY id DESC LIMIT 10");
mysqli_stmt_bind_param($stmt, $section_id);
return mysqli_query($link, $stmt)
}
$result = sectionposts(6);
while ($row = mysqli_fetch_assoc($result)) {
echo $rows['title'] . "<br /><br />";
echo $rows['id'] . "<br /><br />";
echo $rows['image_section'] . "<br />";
echo $rows['subject'] . "<br />";
echo $rows['image_post'] . "<br />";
}
Try this instead, to save yourself a lot of pointless code:
$sql = "SELECT * FROM posts WHERE section_id=$section_id HAVING bar=MAX(bar);"
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo ...;
echo ...;
The having clause lets you find the max record in a single operation, without the inherent raciness of your two-query version. And unless you allow multiple records with the same IDs to pollute your tables, removing the while() loops also makes things far more legible.
Seems like you want to store them in an array.
$posts = array(); //put this before the while loop.
$posts[] = $row; //put this in the while loop
I'm using a multiple select option form to get a table of venues. Each venue has an ID and this is what I used:
<?php
require("db_access.php");
if(isset($_POST['select3']))
{
$aVenues = $_POST['select3'];
if(!isset($aVenues))
{
echo("<p>You didn't select any venues!</p>\n");
}
else
{
$nVenues = count($aVenues);
echo("<p>You selected $nVenues venues: ");
for($i=0; $i < $nVenues; $i++)
{
echo($aVenues[$i] . " ");
}
echo("</p>");
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $aVenues);
echo $comma_separated;
}
}
?>
It results in this:
However I thought that the code would use those two numbers below and draw out a table with those id's I used :/ ? Am I missing something?
$array is used in implode(",", $array); but is not defined anywhere else that we can see. It is perhaps intended to be:
implode(",", $aVenues);
UPDATE
Per comments, it does not draw a table because you never actually query your database.
You build your SQL statement, but you need to execute it and fetch the result set.
// Make sure you actually have a database connection
$conn = mysql_connect('localhost', $username, $password);
mysql_select_db($database);
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $array);
echo $comma_separated;
// Execute query and fetch result rowset
$result = mysql_query($sql);
if ($result) {
$rowset = array();
while ($row = mysql_fetch_array($result)) {
$rowset[] = $row;
}
var_dump($rowset);
}
else echo mysql_error();
I am trying to get the direct path of the $result below:
$query="SELECT videoid from blabla";
$result=mysql_query($query);
$destination="ftp:/.../";
I am trying to get the direct path of the videoid which is in $result so i can send all the actual video files to an ftp.
So far I have:
ftp_put ($connection,$destination,$result,FTP_ASCII);
When I run it it says that the source has to be a string or something like that.
$result is not the field your are looking for, you have to fetch the data from the $result. Note the mysql_fetch_assoc call which pulls data out of the query result.
Here is an example from the mysql_query documentation
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string('fred'),
mysql_real_escape_string('fox'));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
You can therefore modify your code as follows:
$query="SELECT videoid from blabla";
$result=mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
while ($row = mysql_fetch_assoc($result)) {
// loop through every videoid returned, ftp each individually
ftp_put ($connection,$destination,$row['videoid'],FTP_ASCII);
}
mysql_free_result($result);
$query = "SELECT videoid from blabla";
$result = mysql_query( $query );
$row = mysql_fetch_row( $result );
$videoid = $row[0]; // <== there is your videoid
$destination="ftp:/.../";
ftp_put( $connection, $destination, $videoid, FTP_ASCII );
You probably need something like this:
To select one video:
// select all fields, not just the videoid
$query = "SELECT * FROM blabla WHERE videoid = 1"; // replace 1 with actual video id
// or only fields videoid and path
$query = "SELECT videoid, path FROM blabla WHERE videoid = 1"; // replace 1 with actual video id
$result = mysql_query( $query );
$row = mysql_fetch_assoc( $result );
$path = $row[ 'path' ]; // presuming 'path' is the column name
/* do some ftp stuff */
To select all videos:
// select all fields, not just the videoid
$query = "SELECT * FROM blabla";
// or only fields videoid and path
$query = "SELECT videoid, path FROM blabla";
$result = mysql_query( $query );
while( $row = mysql_fetch_assoc( $result ) )
{
$path = $row[ 'path' ]; // presuming 'path' is the column name
/* do some ftp stuff per row */
}
I want to select a row from mysql which matches a specific id. I want to get the result if the ID matches, if the ID does not exists in the database, it should not do anything.
I run sth like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q) or die(mysql_error());
if($result){
$row = mysql_fetch_array($result) or die(mysql_error());
$name = $row['name'];
}
echo "hello".$name;
If the id '1' exists in the db, it should get the name, otherwise nothing or at least it should give the error, but when i use this, it just display no any content of the page which comes after this code. What I'm doing wrong?
If it does not display any code after this code, this is probably due to an error occuring and your error handling being set so the error is not displayed.
Try searching for the php error log file (normaly php_error.log) that should contain the error that you do not see.
Another thing i would try is adding more echo statements to see where exactly php stops interpreting.
Like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q);
echo '<br />Query is send';
if(!$result) {
die('<br/>MySQL Error: ' . mysql_error());
}
else {
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
die('<br/>MySQL Error: ' . mysql_error());
}
}
echo '<br />hello: "' . $name . '"';
That might help to get some more information about your problem.
$id = 1;
$sql = "SELECT `name` FROM `entries` WHERE `id` = $id LIMIT 1" //Since the id is probably an integer type on the DB, the single quotes aren't necessary, and sometimes screw it up. I think MySQL possibly thinks it's a string when in quotes.
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
$row = mysql_fetch_assoc($result) or die(mysql_error());
$name = $row['name'];
echo 'Hello ' . $name;
}
A SELECT query can return 0 rows if the condition you specified doesn't match any rows, and that isn't an error.
You should rather check the result of mysql_num_rows() after sending the query.
Maybe you should add a else statement to your if.
if($result)
....
else
do something
You might even want to do a try catch statement.