PHP - Append db ID to variables - php

What I need to make happen:
I am populating divs with data from mySQL based on the item ID. I need to create variables to be called into the divs such as $tip_ + $id which results in:
$tooltip_1
$tooltip_2
$tooltip_3
What I have done so far:
$query = 'SELECT * FROM top_tips WHERE type = "aw"';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
$tip_ID = $row[0];
$tip_text = $row[2];
$tip_link = $row[3];
$tooltip = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";
echo $tooltip;
}
Where I am stuck:
What is the most efficient way to output $tooltip + $tip_id so the variables can be called into the respective divs?

You would do it like this:
while ($row = mysqli_fetch_row($result)) {
$tip_ID = $row[0];
$tip_text = $row[2];
$tip_link = $row[3];
$tooltip = "tooltip_{$tip_ID}";
$$tooltip = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";
echo "tooltip_{$tip_ID}";
}
That will give you variables such as $tooltip_1, $tooltip_2 and so on. That said, I recommend you use an Array for this.

Added For foreach for your Code..
<?php
$query = 'SELECT * FROM top_tips WHERE type = "aw"';
$result = mysqli_query($link, $query);
while ($results = mysqli_fetch_row($result)) {
foreach($results as $row){
$tip_ID = $row[0];
$tip_text = $row[2];
$tip_link = $row[3];
$tooltip = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";
echo $tooltip;
}
}
?>
Hope you need this solution.. im confused in your question.

You can create an array of $tooltips like so:
$tooltip[] = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";

It seems that you care about efficiency and how to concatenate your $tooltip_ and $tip_ID. First about efficiency, I always learn : When you are fetching results through a loop, never creates variables. Always outside !
In your case, you could create it like this before fetching the results :
<?php
$tooltip_array = array(); //Future array containing your $tooltip_1, $tooltip_2...
$query = 'SELECT * FROM top_tips WHERE type = "aw"';
$result = mysqli_query($link, $query);
Then, in your loop you can push each tooltip onto your array like this :
while ($row = mysqli_fetch_row($result)) {
array_push($tooltip_array,"<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$row[2] . " <a href='" . $row[3] . "'>read more ...</a>");
}
Finally you can echo this out with a foreach loop :
// Iterating through the values
foreach($tooltip_array as $value)
{
echo $value;
}

I wanted to post the working solution I ended up using for anyone reading this thread.
$query = 'SELECT * FROM tool_tips WHERE tip_type = "aw"';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
$tooltip_array[$row[0]] = "<div class='tooltip-close'><a
href='#' class='close'>×</a></div>" .$row[2]. "<a href='" .$row[3]. "'>read more ...</a>";
}
Then I call the individual tooltips like:
<?php echo $tooltip_array[12];?>

Related

How to Remove Slug from my Post , Post.php?Slug=postname-title

I have made a blog in PHP, on Post.php with If isset get I am checking Post ID and than getting slug of same ID from database and accessing the post with that slug.
The issue is its generating Url like: Post.php?Slug=postname-title
I want to make it Post.php?postname-title OR urls.com/postname-title
Please note I am getting post from database matching with slug If any how I do not set php to Get in url it is not getting value from the same slug.
Please guide if it will be done via .htaccess or any other way?
<?php
// add mysql_real_escape_string to slug, to prevent sql injection
$slug = $_GET["slug"];
$sql = "SELECT * FROM posts WHERE slug = '" . mysqli_real_escape_string($db, $_GET["slug"]) . "'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<div id='post-details'>" . "Posted on " . $row["post_date"] . " -- " . "Last Update " . $row["last_edited"] .
"</div>";
if (loggedin()) { echo "<div id='postactions'>This Post:<a href='create_note.php?id=" . $row["id"] . "'>Add Notes</a>";
echo 'Delete Post';
echo 'Edit</div>'; }
$cat_id = $row["cat_id"];
$sql = "SELECT * FROM categories WHERE id = $cat_id";
$resultone = mysqli_query($db, $sql);
if (mysqli_num_rows($resultone) > 0) {
// output data of each row
while ($rowone = mysqli_fetch_assoc($resultone)) {
$cat_name = $rowone["name"];
echo "<div id='post-category'>" . "Category: <a href='all-categories.php?cat_id=$cat_id'>$cat_name</a>" . "</div>";
}
}
echo "<p>" . htmlspecialchars_decode($row["body"]) . "</p>";
$_SESSION["post_id"] = $row["id"];
$postid = $row["id"];
}
} else {
echo "0 results";
}
?>
If you want a simple .htaccess version, you could use the following rule:
RewriteRule ^post/(.+) Post.php?Slug=$1
This will change your URL from a pretty URL like: yourdomain.com/post/postname-title to yourdomain.com/Post.php?Slug=postname-title

Select Data by Id PHP

I have trouble to select a set of specific data using ID from the database. For example, employee one has a unique id of e000000001, when I click the view button in the index will lead to employee detail page which shows the detail of that particular employee instead of all the employees' detail. Thank you.
//from index.php page
<?php
require_once 'db/dbEmpList.php';
$sqlStr = "SELECT * FROM employees;";
$result = $connection->query($sqlStr);
if ($result->num_rows > 0) {
echo "<table class='table table-sm'><thread><tr><th>Full Name</th><th>Employee ID</th><th>Position</th><th>View Employee's Details</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>"
. $row["empName"]. "</td><td>"
. $row["empID"]. "</td><td>"
. $row["position"]. "</td>"
. "<td> <a href='employeedetail.php?id={$row["empID"]}'>View</a>"
. "</td></tr>";
}
}
// from employee page
require_once 'db/dbEmpDetail.php';
$sql = "SELECT * FROM employees where empID = '{$row["empID"]}' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
}
} else {
echo "0 results";
}
mysqli_close($connection);
?>
// FROM EMPLOYEE PAGE
The way you retrieve URL query string is wrong. You should be using $_GET to get the query string from URL. In your case it should be $_GET['id']. See the code below:
require_once 'db/dbEmpDetail.php';
$employeeid = trim(mysqli_real_escape_string($_GET['id']));
$sql = "SELECT * FROM employees where empID = '".$employeeid."' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
}
}
else {
echo "0 results";
}
mysqli_close($connection);
?>

Stop posts from being displayed after certain day

I have just created a pagination function for a travel company. There are two things I want to change that I can't figure out.
Each trip has a date. What i want to be able to do is stop the trip from displaying in the list one the day of the trip and all subsequent days. I have a rough idea, but that doesn't seem to work.
if (date($row['date']) getdate()) {
// echo trip info here
}
-2. After each of the trips in the list there is a seperator (is that the right word?) to separate each trip's info. On the last trip if the page I don't want that seperator. I have no clue how to do this :/
Thanks in advance for any help & advice.
<?php
if (isset($_GET["p"])) { $page = $_GET["p"]; } else { $page=1; };
$start_from = ($page-1) * 4;
$sql = "SELECT * FROM destinations ORDER BY date ASC LIMIT $start_from, 4";
$result = mysqli_query ($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<div class='row'>";
echo "<div class='col-md-4 col-sm-4'>";
echo "<img src='" . $row ['img'] . "' alt='' class='img-responsive'>";
echo "</div>";
echo "<div class='col-md-8 col-sm-8'>";
echo "<h2><a href='" . $row ['url'] . "'>" . $row ['name'] . "</a></h2>";
echo "<ul class='blog-info'>";
echo "<li><i class='icon-calendar'></i> " . date("d/m/y", strtotime($row['date'])) . "</li>";
echo "</ul>";
echo $row ['description'];
echo "<a class='btn theme-btn' href='" . $row ['url'] . "'>View Details <i class='icon-angle-right'></i></a>";
echo "</div>";
echo "</div>";
echo "<hr class='blog-post-sep'>";
}
$sql = "SELECT COUNT(trip_id) FROM destinations";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
$total_pages = ceil($total_records / 4);
echo "<div class='text-center'> <ul class='pagination pagination-centered'>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<li><a href='routea.php?p=".$i."'>".$i."</a></li>";
};
echo "</ul></div>";
mysqli_close($con);
?>
Change your SQL to filter out the unwanted trips:
SELECT * FROM destinations
WHERE date < CURRENT_DATE()
ORDER BY date ASC
LIMIT $start_from, 4
You can solve it with CSS:
hr.blog-post-sep:last-of-type {
display: none;
}

Echo first result from MYSQL differently than all the other results

I have a mysql table in which contains video titles, video embed html, video description, and video thumbnails. I want it to output the first entry as;
$result = mysqli_query($con,"SELECT * FROM entries");
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo $row['html'];
echo $row['desc'];
}
and after that, I would like it to output the next five entries as
$result = mysqli_query($con,"SELECT * FROM entries");
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo "<a href='". $row['id'] . "'><img src='" . $row['thu'] . "'></a>";
}
however I have no idea how to do this. I am kind of a newb when it comes to mysql. Any help would be appreciated.
I have looked at other similar questions but none of them really fit the bill.
Poor man's solution would be something like:
$result = mysqli_query($con,"SELECT * FROM entries");
$first = true;
while($row = mysqli_fetch_array($result)) {
if ($first) {
echo $row['title'], $row['html'], $row['desc'];
$first = false;
continue 2;
}
echo $row['title'], "<a href='{$row[id]}'><img src='{$row[thu]}'></a>";
}
(As explained in PHP chatroom)
Since mysqli_fetch_array() gets you a row, you can use it before the while() without a problem like this
$result = mysqli_query($con,"SELECT * FROM entries");
$row = mysqli_fetch_array($result);
echo $row['title'];
//etc.
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo "<a href='". $row['id'] . "'><img src='" . $row['thu'] . "'></a>";
}
Track it with a sentinel value
$i = 0;
while($row = mysqli_fetch_array($result)) {
if($i == 0){
//first iteration
echo $row['title'];
echo $row['html'];
echo $row['desc'];
}else{
echo $row['title'];
echo "<a href='". $row['id'] . "'><img src='" . $row['thu'] . "'></a>";
}
$i++;//increment value
}

Foreach PHP only one data appear when echo

$selectra_result = mysql_query("SELECT * FROM `my_selectra` WHERE user_id='$user_id'") or die(mysql_error());
while($row = mysql_fetch_array( $selectra_result )) {
$product_id = $row['product_id'];
$namep[] = $product_name= $row['product_name'];
$linkp[] = $product_permalink = $row['product_permalink'];
$imgpp[] = $product_image_path = $row['product_image_path'];
}
foreach($namep as $pname => $prodname){
foreach($linkp as $plink => $prodlink) {
foreach($imgpp as $ppath => $prodpath) {
$res1 = "<a href='$prodlink'><p>$prodname</p></a>";
$res2 = "<a href='$prodlink'><img src='$prodpath'/>";
}
}
}
echo $res2.''.$res1;
}
I want to display data from my_selectra table using foreach, unfortunately it appears only one data when echo.
Your code is pretty convoluted... You don't need 3 arrays to grab the data you want, nor do you need a triple-nested foreach loop structure. Try something like this:
$results = array();
while($row = mysql_fetch_array( $selectra_result))
{
$product_id = $row['product_id'];
$results[] = array( $row['product_name'], $row['product_permalink'], $row['product_image_path']);
}
$res1 = $res2 = '';
foreach( $results as $row)
{
$res1 .= "<a href='" . $row[1] . "'><p>" . $row[0] . "</p></a>";
$res2 .= "<a href='" . $row[1] . "'><img src='" . $row[2] . "'/>";
}
echo $res1 . $res2;
You keep setting $res1 and $res2 with each loop.
I think what you meant to do is $res1 = $res2 = ''; before the loop, then $res1 .= '...'; $res2 .= '...'; inside the loop.
Your echo is in the wrong scope. Place it directly underneath the $res2 variable.
Your code has a lot of double-declarations and variable shifting. I'm not sure you correctly understand basic programming paradigms. You should probably go back to basics, to be honest.
$selectra_result = mysql_query("SELECT * FROM `my_selectra` WHERE user_id='".intval($user_id)."'") or die(mysql_error());
while($row = mysql_fetch_array( $selectra_result )) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$product_image_path = $row['product_image_path'];
$product_permalink = $row['product_permalink'];
echo "<a href='$product_permalink'><p>$product_name</p></a>";
echo "<a href='$product_permalink'><img src='$product_image_path'/>";
}
This is closer to what you are after.
Your query most probably selects only one row from the database (if the id column is unique).
And why a loop (foreach) for each array? Considering that all arrays are created (although this is not very clear, because you don't define the variables in the code provided) in the same loop (while) there is no need to do that...

Categories