I'm using a "foreach" statement to fetch all images from a folder to print on webpage.
I also need to give 'links' to these images.
Links are saved in database table called 'advertisement'.
I fetched all images and displayed correctly.
but I can't make these images as links.
I also used another "foreach" statement to fetch 'link' rows from table 'advertisement' table.
but how to combine these two.
Here is an example of how you could do it:
$files = array('1.jpg','2.jpg');
$stm = $pdo->query('SELECT * FROM advertisement');
$linkInfo = $stm->fetchAll(PDO::FETCH_ASSOC);
$outputArray = array();
foreach( $linkInfo as $row )
{
if( in_array($row['file'], $files) )
{
$outputArray['file'] = $row['link'];
}
}
foreach( $outputArray as $file => $link )
{
echo "<a href='".$link."'><img src='". $file ."'></a>";
}
Not sure how your structure is, but say you have a table like this:
------------------------------
| file | link |
------------------------------
| 1.jpg | http://... |
+
+
+
This should work, with some adjustment according to your own structure.
Related
i have generated a json according to my sql query out put here is my json output, i have listed few of my json code
"42":"",
"field_id_25":"",
"43":null,
"field_ft_25":null,
"44":"",
"field_id_26":"",
"45":null,
"field_ft_26":null,
"46":"",
"field_id_27":"",
"47":null,
"field_ft_27":null,
i have to change json key field_ft_$$ according to my database table values..
|---------------------|------------------|
| field id | field name |
|---------------------|------------------|
| field_id_27 | meta_description |
|---------------------|------------------|
ive coded in php then after i dont know how to finish..
<?php
$con=mysqli_connect("localhost","root","","penn");
if (!$con) {
echo "Failed";
}
// Retrive Data From WebLog Title
$sql="SELECT * FROM `exp_weblog_titles` LEFT JOIN `exp_weblog_data` ON `exp_weblog_data`.`entry_id` = `exp_weblog_titles`.`entry_id` WHERE exp_weblog_titles.weblog_id='13' LIMIT 2 ";
$query=mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($query))
{
$data[] = $row;
}
// Convert The Weblog title data to json
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;
// Retrive web_log_field_List as a array from database
$sql1="SELECT field_id,field_name FROM exp_weblog_fields";
$query1=mysqli_query($con,$sql1);
while ($row1=mysqli_fetch_array($query1)) {
$web_log_field[$row1['field_id']] = $row1['field_name'];
}
// echo $web_log_field[21];
?>
example - i need to change "field_ft_27":null to "meta_description": null and others according to my database values
Use a regular expression to extract the appropriate parts of field_ft_XX and get the corresponding field_id_XX element of $web_log_field. Then you can delete the old key and add the replacement key.
foreach ($data as &$row) {
foreach ($row as $key => $value) {
if (preg_match('/^field_ft_(\d+)$/', $key)) {
$idkey = "field_id_$key[1]";
if (isset($web_log_field[$idkey])) {
$row[$web_log_field[$idkey]] = $value;
unset($row[$key]);
}
}
}
}
So I have a tv show website and I created custom lists where you can add whatever tv shows you want.
There is one table called lists (with user_id, list_title) and another table called show_lists which contains (list_id, show_id).
So my PHP is there:
<?php
$findlistsq = $conn->prepare('SELECT * FROM show_lists, shows, lists
WHERE lists.user_id = :user_id AND
lists.list_id = show_lists.list_id AND
shows.id = show_lists.show_id');
$findlistsq->execute(array(':user_id' => 2));
$listscount = $findlistsq->rowCount();
echo $listscount;
$list = array();
while ($listarray = $findlistsq->fetch()) {
$list[$listarray['list_title']][$listarray['name']] = $listarray;
}
?>
<?php
foreach ($list as $key => $show) {
echo $key; //echo title of list
foreach ($show as $key => $value) {
echo $value['name']; //echo tv shows
;
}
}
?>
Basically, I create an array to join a list to its tv shows, display the title of the list and whatever it contains and so on. My question is: I want to display the list only if there is more than 3 shows (at least 3 different $value).
Can anybody tell me how I could do that ? Thanks!!
Edit: Also, there is slight chance that I might have overcomplicated this. Let me know if I did.
Your explanation of your data is not great, but you could try doing this in the SELECT statement, this will be faster than messing with arrays.
$findlistsq = $conn->prepare('SELECT *
FROM show_lists, shows, lists
WHERE
lists.user_id = :user_id AND
lists.list_id = show_lists.list_id AND
shows.id = show_lists.show_id AND
COUNT(DISTINCT shows.id) > 3');
This will count the DISTINCT (unique) show ids and only return you a data set if there are more than 3 DISTINCT show ids.
You will want to look into is_array() and count()
$list = array('show1','show2','show3');
if(is_array($list)){
if(count($list) > 3){
//more than 3 shows found, execute code!
}
}
I want to run a query that gets all the data from a database then have the data split into arrays for each column. With this I intend to dynamically populate html. I am not very experienced with php and could use some assistance with how to put my query into multiple arrays depending on what column it was in.
Example: For the column name I want an array $itemName[] and it will contain every item name in asc order. Then for the image column I want an array $itemImage[] for every image/image url in the same order.
With this I plan to run a for loop where as x increases it will go through each diff array and pull from the specified location. There are no null values in my DB so I don't need to worry about that.
Any help you can give me with the writing the query into multiple arrays based on the column name is appreciated.
$mPos = array(mPos1, mPos2, mPos3, mPos4);
for (x=0; x<4; x++){
echo "<div class="$mPos[x]"> <div class="$mPos[x] . '_1'">"$title[x]"</div><div class="$mPos1 . '_2'">"$image[x]"</div>
Still doesn't make sense for me to separate it that way, but here you go.
Since you didn't provide a database/table structure, I will assume your db table got the following columns:
itemId | itemName | itemImage | itemDescription
In PHP you loop through the result row for row and populate your arrays like
foreach ( $result AS $row ) {
$itemNames[$row->itemId] = $row->itemName;
$itemImages[$row->itemId] = $row->itemImage;
$itemDescriptions[$row->itemId] = $row->itemDescription;
}
EDIT: After question was updated and now includes the HTML output, I'd suggest something like this.
foreach ( $result AS $row ) {
$items[$row->itemId] = array(
'name' => $row->itemName,
'image' => $row->itemImage,
'description' => $row->itemDescription,
'price' => $row->itemPrice,
'link' => $row->itemLink,
);
}
$x = 0;
while ($x<4) {
$x++;
$item = array_shift($items);
echo '<div class="mPos'.$x.'">
<div class="mPos'.$x.'_1">"'.$item['name'].'"</div>
<div class="mPos'.$x.'_2">"'.$item['price'].'"</div>
<div class="mPos'.$x.'_3"><a href="'.$item['link'].'">
<img src="'.$item['image'].'" /></a>
</div>
</div>';
}
$sth = $dbh->prepare("SELECT itemName, itemImage FROM myTable");
$sth->execute();
$result = $sth->fetchAll();
$myArr = array();
foreach($result as $row){
foreach($row as $colName => $colVal){
$myArr[$colName][] => $colVal;
}
}
echo '<pre>';
print_r($myArr);
echo '</pre>';
Although I do have misgivings about how you're actually approaching this from a design perspective.
I'm failing miserably to get my head around what I know ought to be simple, and am unsure if the solution lies in the query or in processing the result, so struggling to search for what I'm sure has been covered in another post.
I'm working with a single MySQL table, from which I need to be able to retrieve and process content that shares a common ID. Unfortunately, restructuring the database isn't an option.
Here's what a simple SELECT * WHERE contentID = '2' query returns:
|contentType|contentID|content |
--------------------------------------
|title |2 |<h1>title</h1>|
|intro |2 |<p>intro</p> |
|main |2 |<p>main</p> |
What's the correct way to retrieve the specific 'title', 'intro' or 'main' content?
Thanks in advance.
$result = mysql_query("SELECT * WHERE contentID = '2'");
$array = array();
while($rows = mysql_fetch_array($result,MYSQLI_ASSOC)){
$array[$rows['contentType']] = $rows['content'];
}
You can use the $array for each content type
Fetch all the rows into an array:
$data = array();
foreach ($rows as $r) {
$data[$r['contentType']] = $r['content'];
}
You'd have to put your content type into the where clause. The Id and type should form a natural ok and should be constrained as such. If not, time to redesign. Also, id consider putting the content type as a lookup rather than a string.
<?php
function executeQuery($query,$connectionObject)
{
queryString=$query;
recordSet=mysql_query(queryString,$connectionObject);
if(!$recordSet)
{
$errorString=mysql_error($this->connectionObject);
return array("error"=>$errorString);
}
return recordSet;
}
function getNextRecord($recordSet)
{
$resultArray =mysql_fetch_assoc($recordSet);
if(!empty($resultArray))
return($resultArray);
else
return "false";
}
$result = executeQuery("SELECT * FROM foo WHERE contentID = '2'");
$nextRecord = getNextRecord($result);
while($nextRecord!="false")
{
$nextRecord = getNextRecord($result);
//...........Process the record.....
->$nextRecord['contentType'];
->$nextRecord['contentID'];
->$nextRecord['content'];
//..................................
}
I am going to select a list of items from a table, and pass it using json-framework.
Example, I want to select friends from my "shirts" table, from "players_shirts" table
pid | sid
================
1 | 2
2 | 3
1 | 5
Lets say, I get 30++ result (rows).
I assume (not yet tested this code), in php, I assign it by:
$array;
$count = 0;
while($r = mysql_fetch_assoc($exe){
$array[$count] = $r['sid'];
// EDIT START: I forgot to add counter
$count++;
// EDIT END
}
echo json_encode($array)
Is this method efficient/good enough?
I am new to php/database/manipulating data from database.
There is no need to specify an array keys in your case, so your code could be rewritten as:
$array = array();
while($r = mysql_fetch_assoc($exe){
$array[] = $r['sid'];
// or you may use array_push($array, $r['sid']); instead of the line above.
}