echo specific row from array - php

I currently have a table like the one below.
ID adPlacement filePath dateAdded adName adLink
12 1 Test 1.png 2013-02-12 Test 1 http://www.cuad.coop
13 1 Test 2.png 2013-02-12 Test 2 http://www.google.com
I am trying to randomly select a row and echo out the adName, adLink, and filePath all on separate echo statements.
Here is the code I am using right now:
$query_adSpot1 = "SELECT * FROM advertisements WHERE adPlacement = 1";
$result = mysql_query($query_adSpot1, $server) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$row = array(
'adName' => $row['adName'],
'filePath' => $row['filePath'],
'adLink' => $row['adLink']
);
$fileLocation = $row;
$fileLocations[] = $fileLocation;
}
shuffle($fileLocation);
echo $fileLocation[0];
Right now when I run the script it will write test 2.png, or test 2, or http://www.google.com.
I want to be able to echo separately from a random row, but need the separate columns to equal same row.
echo filePath
echo adName
echo adLink

You are shuffling the wrong array, you should be using:
shuffle($fileLocations);
^ This is the one with all your values
var_dump($fileLocations[0]);
// will show you an array with 3 elements from the same row in the database
What you are doing is re-ordering the last row found in your sql query.

You can use the RAND()function in MySQL
$query_adSpot1 = "SELECT * FROM advertisements WHERE adPlacement = 1 ORDER BY RAND() LIMIT 1";
$result = mysql_query($query_adSpot1, $server) or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row['filePath'];
echo $row['adName'];
echo $row['adLink'];

Related

Output is array, how to fix this?

Right now I am selecting some data from Mysql which I want to echo out, but I don't know how..
Code
<?php
// Database connection
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/opendb.php");
// News 1
$searchroutenews1 = "SELECT newsid FROM NewsHomepage WHERE id = '1'";
$handlenews1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews1);
$news1 = mysqli_fetch_row($handlenews1);
$searchroutenewsimg1 = "SELECT newsimg FROM NewsHomepage WHERE id = '1'";
$handlenewsimg1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg1);
$NewsImg1 = mysqli_fetch_row($handlenewsimg1);
// News 2
$searchroutenews2 = "SELECT newsid FROM NewsHomepage WHERE id = '2'";
$handlenews2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews2);
$news2 = mysqli_fetch_row($handlenews2);
$searchroutenewsimg2 = "SELECT newsimg FROM NewsHomepage WHERE id = '2'";
$handlenewsimg2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg2);
$NewsImg2 = mysqli_fetch_row($handlenewsimg2);
// News 3
$searchroutenews3 = "SELECT newsid FROM NewsHomepage WHERE id = '3'";
$handlenews3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews3);
$news3 = mysqli_fetch_row($handlenews3);
$searchroutenewsimg3 = "SELECT newsimg FROM NewsHomepage WHERE id = '3'";
$handlenewsimg3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg3);
$NewsImg3 = mysqli_fetch_row($handlenewsimg3);
?>
After this I require_once this in an other file, and then I echo the variables $news1, $news2, $news3, $NewsImg1, $NewsImg2 and $NewsImg3. But if I echo this variables out now it says: array.
You can fetch all this information via a single query, instead of the 6 you currently are running. Then it's a matter of putting mysqli_fetch_*() as the argument of a while, as you'll then fetch all the rows, until that function returns null - at which point you've fetched all the rows returned by the query.
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT newsid, newsimg FROM NewsHomepage WHERE id IN (1, 2, 3)");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['newsid']." ".$row['newsimg'];
}
Change however you need it to be displayed inside the while loop, and use the two variables as they are inside.
Alternatively, you can use WHERE id BETWEEN 1 AND 3 instead, but using IN (1, 2, 3) can more easily be changed to the exact ids you need.
http://php.net/mysqli-result.fetch-assoc
First you should read http://php.net/manual/en/mysqli-result.fetch-row.php
you can find there mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array mysqli_fetch_row always return array so now you can't echo array thats why it gives you array.
You can try foreach loop or for loop or while loop to display your data. there are also various methods to get array value.
Below is an example you can use.
while ($news1 = mysqli_fetch_row($handlenews1)) {
echo $news1[0];
}

count database rows by id

I'm trying to count the $active_ids from the database. But I'm not figuring out how to do it best. As a disclaimer, I'm still learning MySQL/PHP.
this is what it echo's right now
1, 3, 4, 1, 1
and is what it will look like if it's counted
3, 1 ,1
<?php
$active_ids = '1, 3, 4';
$query = "SELECT * FROM users WHERE id IN ({$active_ids})";
$result = $mysqli->query($query);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $row['username'], "<br/>";
}
$query = "SELECT COUNT(*) FROM timetable WHERE dj IN ({$active_ids})";
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()){
echo $row['dj'], "<br/>";
}
}
?>
I don't really know PHP, but I know SQL. It sounds like you want to use a GROUP BY clause, like this:
select dj, count(*) as n from timetable
where dj in ({$active_ids})
group by dj
Each row selected will have two columns. The first column (named “dj”) is the dj's user id, and the second column (named “n”) is the number of entries in timetable with that dj's id. You should be able to print the count like this:
echo $row['n'], "<br/>";

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

PHP - Multiple MySQL result, in separate variables

I need to do a MySQL query to search for an inexact match / match containing the submitted value.
The following is an example of what is in my database:
id img
1 1001_ABC_01.jpg
2 1001_ABC_02.jpg
3 1002_ABC_01.jpg
4 1002_ABC_02.jpg
5 1002_ABC_03.jpg
6 1002_ABC_04.jpg
7 1002_ABC_05.jpg
8 1003_ABC_01.jpg
9 1003_ABC_02.jpg
10 1003_ABC_03.jpg
I need the query to search for the first part of the filename (1002) and and assign each returned result in the img field a different variable. The maximum amount of variables would be 5.
For example, if I search 1002, it should assign the following variables:
<?php
$img1 = '1002_ABC_01.jpg';
$img2 = '1002_ABC_02.jpg';
$img3 = '1002_ABC_03.jpg';
$img4 = '1002_ABC_04.jpg';
$img5 = '1002_ABC_05.jpg';
?>
so that way I can echo each filename result individually.
Again, the maximum amount of variables here will be 5, so if more than 5 results are returned, only the first 5 will be assigned variables.
Please let me know if this is possible and how to write a PHP script to do it.
SELECT img FROM <table_name> WHERE img LIKE '%search%' ORDER BY ID DESC LIMIT 5;
You could substring function, if the first four integers are fixed like this:
select substring(img,1,4) from <table_name> where img = 'search' order by ID DESC limit 5;
I hope this will help you. Always try to use latest apis and function like MySqli try to avoid mysql_* functions because they are depreciated and MySqli is also faster then mysql_ functions
$img = '1002'; // For example
$connection = new Mysqli(host, user, password, database);
$sql = "SELECT img FROM <table_name> WHERE img LIKE '$img%' LIMIT 5";
if($connection->query($sql)){
$counter = 1;
while ($row = $connection->fetch_object()){
${'img'.$counter} = $row->img;
$counter++;
}
}
$query = "SELECT * FROM my_table WHERE img_name LIKE '%1002%' LIMIT 5";
foreach ( $fetched_row as $value ) {
echo $value [ 'img_name' ]; // or whatever you want to do
}
Something like that.
Use this query
SELECT img as IMG
FROM my_table
WHERE img LIKE '1002%'
order by id desc
LIMIT 5
<?php
$query="SELECT id,img as image FROM image_table
where img like '%$keyword%' limit 5";
$res=mysql_query($query) or die(mysql_error());
while ($img = mysql_fetch_array($res)) {
echo $img['image'];
}
?>
$con = new Mysqli(host, user, password, database);
$result = $con->query("SELECT * FROM table WHERE image LIKE %$search% ORDER BY id DESC LIMIT 5");
if($result){
while ($row = $con->fetch_object()){
$img_arr[] = $row;
}
}
I hope this will help you.
$queryStr = "SELECT img FROM table_name WHERE search_str LIKE '1002%'";
$query = mysql_query($queryStr);
while($row = mysql_fetch_assoc($query)){
$imageArray[] = $row;
}
// Print the array
echo '<pre>';
print_r($imageArray);
echo '</pre>';
// How to use the array
foreach($imageArray as $key=>$val){
echo 'File Name: '.$val;
echo '<br />';
echo '<img src="'.$val.'" />';
echo '<hr />';
}
// Now show first five result
// Alternet: You can use LIMIT and order by with mysql
// With php
for($i=0;$i<5;$i++){
echo 'File Name: '.$imageArray[$i];
echo '<br />';
echo '<img src="'.$imageArray[$i].'" />';
echo '<hr />';
}
To search for a partial match you can use the LIKE operator in SQL. In this case you could write:
$sql = "SELECT img FROM tablename WHERE img like '1002%'";
How to perform this query and obtain the results in PHP depends on the database API you are using: old MySQL? MySQLi? PDO? Also, 1002 is probably user input, in which case you have to protect your program against SQL injection attacks.
As to the second part, are you sure you want different variable names and not an array? Arrays are much easier to use. You can get different variable names if you first accumulate the data in an array and then use extract:
$result = array();
$counter = 1;
$rs = mysql_query($sql); // using old mysql API
while ($row = mysql_fetch_array($rs)) {
$result["img".$counter] = $row[0];
$counter = $counter + 1;
}
extract($result);
// now $img1, $img2, $img3, ... are defined
your code will look like this:
$input = '1002'; // For example
$query = "SELECT id, img FROM table_blah WHERE img LIKE '$input%' LIMIT 5";
This query is basically selecting id, and img from the table table_blah, and img must be the same as 1002, and % meaning absolutely anything from there on. Limited to 5 results.
Then:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
// Code for each result here.
// id = $row['id']
// img = $row['img']
}
$query = "SELECT * FROM img_table WHERE img_name regexp concat('1002', '%')"
$results = mysql_query($query);
then $results is an array of img strings

php and mysql selecting 5 rows from mysql

i am tryng to select 5 mysql rows from the database and display them like $row[1] ect.... in php i am not sure how to do it an someone lead me down the right way please
Ok i hav looked a bit more
i wanted it to come out 1 - 5 and i wanted it to display the names
$result = mysql_query("SELECT * FROM table ORDER BY id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
$arr = array("somearray" => array(1 => 5, 2 => 9, 3 => 42, 4 => 42, 5 => 42));
echo $arr["somearray"][1];
echo $arr["somearray"][2];
echo $arr["somearray"][3];
echo $arr["somearray"][4];
echo $arr["somearray"][5];
}
I think the OP wants five ROWS, not COLUMNS. Here is the correct code, assuming you already have a mysql connection open:
$sql = 'SELECT *
FROM table_name
ORDER BY col_name
LIMIT 5';
$result = mysql_query($sql);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row[] = $line;
}
// print (access individual rows: $row[0] ... $row[4])
var_dump($row);
From php.net :
http://us3.php.net/manual/en/function.mysql-fetch-row.php
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Try using MySQL's LIMIT clause to limit your results to 5 rows. And use PHP's mysql_fetch_assoc() (returns an associative array) instead of mysql_fetch_row() (returns a numerically indexed array). Also, it's good practice to free the memory associated with the result using mysql_free_result().
$result = mysql_query("SELECT * FROM mytable ORDER BY id DESC LIMIT 5") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
echo $name;
}
mysql_free_result($result);
If you only need to select 5 rows from MySQL you can do this:
SELECT *
FROM Table
ORDER BY column
LIMIT 5

Categories