detect if array value contains specific text PHP - php

I have a SQLite- database containing articles. All articles contains HTML, but one of those articles contain an <aside>. So I'd like to present this article in another way than the others.
This is my code now:
$db = new PDO("sqlite:$dbPath");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // Display errors, but continue script
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<table id="artikelLista">
<caption><em>Visar alla artiklar</em></caption>
<?php foreach($res as $article): ?>
<tr class="artikelContent">
<td><h4><?php echo $article['title']; ?></h4>
<?php echo $article['content']; ?>
<span class="floatRight"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></span></td>
</tr>
<?php endforeach; ?>
</table>
Is there a way to check if the $article['content] array value contains "<aside>" and set a different style for that tr? (Or div if this is not possible inside tr)

All you need to do is:
if(strpos($article['content'],"<aside>") == false) {
//is <aside> is not present
} else {
//if word detected
}

Related

PHP - output associate array into HTML <div>s with labels/headings

I have a PHP function that returns a single row from a localhost MySQL table like so:
<?php
//include database connection process
require_once("includes/conn.inc.php");
//prepare statement
$stmt = $conn->prepare("Select * FROM races WHERE raceID = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>
What I would like to do with this array is output the data from the individual fields in their own HTML <div> or <p> with a heading indicating what they mean in a separate div. I currently user the print_row method that outputs everything in one. All the data I want is there, but I'd like it separated out into name/value paragraphs or divs.
//what I currently have
<?php
print_r($row);
?>
Is there a way to do this?
Thanks in advance,
Mark
I didn't understand the question very well but I think I understand what you need.
Use while to iterate trough each row.
while($row = $resultDesc->fetch_assoc())
{
echo '<p><strong>Description:</strong></p> ';
echo '<p>'. $row['description'] . '</p>';
}
That's not the exact solution but atleast shows you the path.
You can use foreach
<?php foreach ($row as $key => $val): ?>
<p><strong><?php echo $key; ?>:</strong></p>
<p>
<?php
//output relevant attribute
//of query run on page load
echo $val;
?>
</p>
<?php endforeach; ?>

I am using two tables from database and to display on a page using PHP

I am trying to make a page which has to get data from two tables. and display on a page. this displayed data is an array. for example if the displayed data is say USA which come from Table A,and if you click on USA...then it should go to Table B and get all the states from Table B related to USA and display it on the page. so how to join the tables?
the code used is as below:
<?php
require("libs/config.php");
$pageDetails = getPageDetailsByName($currentPage);
$stateDetails = getStateDetailsById($page_id);
include("header.php");
?>
<div class="row main-row">
<div class="col-md-8">
<section class="left-content">
<h2><?php echo stripslashes($pageDetails["page_title"]); ?></h2>
<?php echo stripslashes($pageDetails["page_desc"]); ?>
<!--New-->
<?php
$page_id = $pageDetails["page_id"];
if ($_GET["id"] <> "")
{
// if we are on page.php page. get the parent id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE status = 'A' AND parent = :parent ORDER BY sort_order ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($pageDetails["parent"]));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
?>
<div class="col-sm-12">
<?php
if (count($pageResults) > 0)
{
?>
<section>
<h2>States</h2>
<div>
<div class="row">
<?php foreach ($pageResults as $rs)
{ ?>
<div class="col-sm-3">
<ul class="state">
<li class="state">
<div class="state-dist"><h3><?php echo stripslashes($rs["page_title"]);?></h3>
<div class="state_img"><img src="images/<?php echo stripslashes($rs["page_image"]);?>"height="50" width="180"</div>
<br />
<br />
<div class="page-actions">
More Details
</div>
</li>
</ul>
</div>
<?php } ?>
</div>
</div>
</section>
<?php } ?>
</section>
</div>
So,
when i click on the link created by the last part of the code then it should go to TABLE.STATES fetch the records and display it. Currently this code goes to the same table TABLE_PAGES.
I know i have to use table joins but I am not able to code it.
Currently this code goes to the same table TABLE_PAGES.
As far as I think, you should change TABLE_PAGES to TABLE_STATES in the following part of your code:
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_STATES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
I'm assuming you'll be running the following SQL code:
SELECT * FROM TABLE_STATES WHERE TABLE_STATES.page_id = TABLE_PAGES.page_id
which you can execute to get a list of all the states belonging to the parent (TABLE_PAGES) table.
TIP: Always try to use table names that represent real-world entities AND serve the purpose of the actual data that you want to store. In your case TABLE_COUNTRIES would be a more conventional name for a table that represents the entity country.
You could also run a left join as such:
SELECT TABLE_STATES.* LEFT JOIN TABLE_COUNTRIES ON TABLE_COUNTRIES.page_id = TABLE_STATES.page_id AND TABLE_COUNTRIES.page_id = <your provided value>

Create a News Feed that displays posts from people they are following

I have a code that should check the Database following to find all the people that the current logged in user has followed then it will search the second database posts to find any posts by the people they are following but it currently only shows one post. I know its not very efficient compared to JOIN but I don't fully understand how that works.
Here is a Screenshot of the Database Following it has the user who sent the following request and the user they are following what is it should do is use the session id for the logged in user and find all matching results for the user in the following column and it should take all the results from the column following and search the database post in the column code and echo all the results as the newsfeed.
<?php
$con=mysqli_connect("HOST","USERNAME","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myid=$_SESSION['user']['id'];
$result = mysqli_query($con,"SELECT * FROM following WHERE follower='$myid'");
while($row = mysqli_fetch_array($result)) {
$following=$row['following'];
?>
<?php
$con=mysqli_connect("HOST","USERNAME","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM posts");
while($row = mysqli_fetch_array($result)) {
if ($following==$row['code']){
?>
<div class="content">
<section class="intro">
<h2><?php echo $row['name']; ?> <?php echo $row['lastname']; ?></h2>
<div class="text">
<?php echo $row['post']; ?>
</div>
<?php
}
else{
}
}
mysqli_close($con);
?>
<?php
}
mysqli_close($con);
?>
Because my previouse answer didnt help What do you want to output??
If your database has 3 followers does it have to output this in html?
But this Code will Output All users in your following list Like this..
$result = mysqli_query($con,"SELECT * FROM posts");
echo "<div class='content'> <section class='intro'>";
echo "<h2><a href='/profile/?id=".$row['code']."'>";
while($row = mysqli_fetch_array($result)) {
if ($following==$row['code']){
echo $row['name']." ".$row['lastname']."</a></h2>";
echo $row['post'];
}
echo "<div class='text'>";
echo "</div>";
}
This Code is Outputting this but the Bold text in this example is a link that goes to
/profile/?id=CODEHERE
Steve Jobs <-- is a link (goes to /profile/?id=CODEHERE
The Post text
Johny John
The Post text
Miracle Tru
The Post text

random image not working correctly

i have create an array to diusplay a random file name from my mysql database. unfortunatly it doesnt show correctly.
i need the explode to work based on file id to show the correct banner picturse for that tv series.
<?php include '../connect/dbseries.php' ?>
<?php include 'Sbarray.php' ?>
<?php
$names = explode ("|", $row['4']);
?>
<center><?php
while($row=mysql_fetch_array($result2)){
echo '<img src="../images/series/'. $names[array_rand($names,1)].'" width="800" height="150" style="padding:2px;">';
}
?>
</center>
my array page is
<?php $result2 = mysql_query("SELECT
ID,
pretty_name,
sortname,
Genre,
Bannerfilenames,
CurrentBannerFilename,
Posterfilenames,
PosterBannerFileName,
summary,
Fanart,
IMDB_ID
FROM online_series
order by sortname ASC;");
if (!$result2) {
echo 'Could not run query: ' . mysql_error();
exit;
}
?>
<?php $row = mysql_fetch_row($result2);
//setup array
$banner = $row['4'];
?>
that is all the code i have on the page. any help would be appreciated as it only shows images from row 1 instead of for each row/ tv series
i asume it has something to do with the explode command but cant figure out how to correct it.
thanks in advance
you can check with print_r($names) whether it works. If I understand your problem correctly, you want a random pic of each row. Now you do the variable names before you iterating through the results - so it uses always the first:
<?php $result2 = mysql_query("SELECT
ID,
pretty_name,
sortname,
Genre,
Bannerfilenames,
CurrentBannerFilename,
Posterfilenames,
PosterBannerFileName,
summary,
Fanart,
IMDB_ID
FROM online_series
order by sortname ASC;");
if (!$result2) {
echo 'Could not run query: ' . mysql_error();
exit;
}
?>
<center><?php
while($row=mysql_fetch_assoc($result2)){
$names = explode ("|", $row['Bannerfilenames']);
//for check whether explode works
print_r($names);
echo '<img src="../images/series/'. $names[array_rand($names,1)].'" width="800" height="150" style="padding:2px;">';
}
?>

PHP My SQL Database table not visible

I am beginner to PHP and mySQL. I am creating a navigation trough my database. I have two tables set up one is the main nav items and one is the sub nav items. They are connected by the subject_id. I am using a loop to display them. The first table displays and the second table leaves space for where the information should be but it does not show up. I think it must be something in the SQL settings but I have no idea. Here is my code(i know the database is connected):
<?php require_once("includes/connection.php") ?>
<?php require_once("includes/functions.php") ?>
<?php include("includes/headder.php") ?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = mysql_query("SELECT * FROM subjects", $connection);
if(!$subject_set){
die("database query failed: " . mysql_error());
}
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li>" . $subject["menu_name"] . "</li>";
$page_set = mysql_query("SELECT * FROM pages WHERE subject_id = {$subject["id"]}", $connection);
if(!$page_set){
die("database query failed: " . mysql_error());
}
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li>" . $page["menu_name"] . "</li>";
}
echo "</ul>";
}
?>
</ul>
</td>
<td id="page">
<h2>Content Area</h2>
</td>
</tr>
</table>
<?php include("includes/footer.php") ?>
Since you mentioned that white space is showing where the data should be, it appears that rows are indeed found. Consequently, your select statement should be ok. This most likely means that the index "menu_name" can't be found on the $page record.
Check to make sure that "menu_name" is indeed a column of the pages table.
To test what valid columns the $page record has you can use the following inside the while $page loop:
var_dump($page);
If the subject id is an integer you do not need single quotes in the where clause. However, if the subject_id contains any non-integer characters, your select statement would need to be:
$page_set = mysql_query("SELECT * FROM pages WHERE subject_id = '{$subject["id"]}'", $connection);

Categories