use string for select statement in database pdo php - php

This is just a thought i have for my project is it possible to use a string for example an echo as parameter for select statement in database query?
here is the scenario:
For example when my page loads i automatically display the latest data in database say last five entry, as echo of course. and for each entry there are other details and in order to view those other details i will have an anchor for each echo and i will direct the user to another page..using the echo i want to query the database for other details..
Is this possible?
I know I cant put attribute name to echo so how is this possible?
Any suggestions?
Update
this is the page that will show the echo
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<div class="headerimage"><img src="images/events.png"/></div>
<?php
foreach (LoadEvent() as $value){
echo '<div id="upcomingevent">';
//echo "<a href=\"#\" >".$value['searchresultwhat']."</a>";
echo "".$value['searchresultwhat']."";
echo "<input type='hidden' name=\"eventwhatcontent\" value=".$value['searchresultwhat'].">";
echo "<br/>\n";
echo $value['searchresultwhen'];
echo "<br/>\n";
echo $value['searchresultwhere'];
echo '</div>';
}
?>
</form>
then this is the method and the page where i must display the details of the event
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<?php
echo '<div id="middlecontentupcomingevents">';
LoadSpecificEvent();
echo '<div id="upcomingeventcontentimage">';
echo "<img src=\"admin/".$events[4]."\">";
echo $events[0];
echo $events[1];
echo $events[2];
echo $events[3];
echo '</div>';
echo "<br/>\n";
echo '</div>';
echo '</div>';
?>
</form>
function LoadSpecificEvent(){
global $dbh;
//var_dump($dbh);
if (isset($_POST['eventwhatcontent'])) {
$eventwhat = $_POST['eventwhatcontent'];
$stmt = $dbh->prepare("SELECT * FROM events WHERE event_what = ?");
$stmt->bindValue(1,$eventwhat);
$stmt->execute();
$events = array();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
$events[] = array(
'searchresultwhat' => $selected_row['event_what'],
'searchresultwhere' => $selected_row['event_where'],
'searchresultwhen' => $selected_row['event_when'],
'searchresultwho' => $selected_row['event_who'],
'searchresultimg' => $selected_row['img_url']
);
print_r ($events);
return $events;
}
}

Related

SQL While loop select all rows that have a column checked

I'm trying to do a featured car section in my used car lot website.
What I want to do is to use a while loop and select only the rows that have a specific column that returns true. For example, in my database, I have a column that is marked true if a checkbox on the submit form is ticked indicating that the car is supposed to be "featured".
In my while loop I only want those cars to appear in this particular section. Using the code below, I can return all vehicles in the inventory but no way to select only the ones with the "featured" column that returns a true value.
<?php
$sql = "SELECT * FROM inventory LIMIT 10";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc())
{
echo '<div class="slide">';
echo '<div class="car-block">';
echo '<div class="img-flex">';
echo '<a href="inventory-listing.php?vin='.$row['vin'].'">';
echo '<span class="align-center">';
echo '<i class="fa fa-3x fa-plus-square-o"></i></span></a>';
echo '<img src="images/inventory/'.$row['vin'].'-main.png" alt="" class="img-responsive">';
echo '</div>';
echo '<div class="car-block-bottom">';
echo '<h6><strong>'.$row['year'].' '.$row['make'].' '.$row['model'].'</strong></h6>';
echo '<h6>'.$row['body'].', '.$row['milage'].' miles</h6>';
echo '<h5>$ '.$row['price'].'</h5>';
echo '</div>';
echo '</div>';
echo '</div>';
}
?>
What would I be able to add to my sql query to filter it only the rows where the "featured" column returns true?
Alternative to Goleztrols suggestion, you could just insert an IF clause before echo-ing the results.
<?php
$sql = "SELECT * FROM inventory LIMIT 10";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc())
{
if ($row['featured']=="true")
{
echo '<div class="slide">';
echo '<div class="car-block">';
echo '<div class="img-flex">';
echo '<a href="inventory-listing.php?vin='.$row['vin'].'">';
echo '<span class="align-center">';
echo '<i class="fa fa-3x fa-plus-square-o"></i></span></a>';
echo '<img src="images/inventory/'.$row['vin'].'-main.png" alt="" class="img-responsive">';
echo '</div>';
echo '<div class="car-block-bottom">';
echo '<h6><strong>'.$row['year'].' '.$row['make'].' '.$row['model'].'</strong></h6>';
echo '<h6>'.$row['body'].', '.$row['milage'].' miles</h6>';
echo '<h5>$ '.$row['price'].'</h5>';
echo '</div>';
echo '</div>';
echo '</div>';
}
else
{
echo "nothing to be shown";
}
}

How generate hyperlinks for news show in codeigniter

i created a news panel where we use this code for displaying news :
<marquee direction="up" >
<?php
$query = $this->db->get('news');
foreach ($query->result() as $row)
{
echo $row->news;
echo $row->urladdress;
echo '<br/>';
}
?>
</marquee>
where it show correct , all data get fetched and run marquee good ,
but we tried ,when we click on news then it go urladdress , which fetch from table . By using this code but not work -
<marquee direction="up" >
<?php
$query = $this->db->get('student');
foreach ($query->result() as $row)
{
echo $row->news;
echo $row->urladdress;
echo 'click here';
echo '<br/>';
}
</marquee>
Read CI anchor
echo anchor($row->urladdress, 'click here', 'title="click here"');
its "" not '' to echo value of field
echo "<a href='$row->urladdress'>click here</a>";
OR
echo 'click here';
<marquee direction="up" >
<?php
$query = $this->db->get('student');
foreach ($query->result() as $row)
{
echo $row->news;
echo $row->urladdress;
echo 'click here';
echo '<br/>';
}
?>

How to Detect a Button Click in an Expanded Accordion Row with Multiple Labels

This is an extension to another post by myself (How To Detect a Button Click in the Expanded Accordion Row).
After adding some additional rows in the details section of my accordion control and moving the 'Select' button into a separate div, I am only getting the values from the first accordion row. This was my original issue. Just to confirm the original solution worked, if I move my 'Select' button into the save div containing the label for Location, it passes the correct location label ('labelAccordionLocation') value for what ever row I have expanded but always passes the first row's name label value. It also works correct if the 'Select' button is in the save div as the Name label ('labelAccordionName').
Based on the suggestion in my other post (which worked flawlessly for my original example), it seems that I now need to figure out how to identify the div that contains each label so I can then pass it's value when the 'Submit' button is clicked. Although, this is still just an amateur's way of thinking.
<div class="accordion" id="accordion2">
<?php
// SQL stuff here...
$group = null;
while ($row = odbc_fetch_array($db)) {
if ($row['Name'] != $group) {
echo "<div class='accordion-heading'>";
echo "<a class='accordion-toggle' data-toggle='collapse'
data-parent='#accordion2' href='#", $row['Number'],"'>
<button id='buttonAccordionToggle'
data-target='#", $row['Number'],"'>", $row['Name'],"</button></a>";
echo "</div>";
echo "<div id='", $row['Number'],"' class='accordion-body collapse'>";
echo "<div class='accordion-inner'>";
echo "<div class='control-group' style='min-height: 50px'>";
echo "<div class='row-fluid show-grid'>";
echo "<div class='span12'>";
echo "<div class='span1'>";
echo "<label>Name:</label>";
echo "</div>";
echo "<div class='span11'>";
echo "<label id='labelAccordionName'>",
$row['Name'],"</label>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<div class='row-fluid show-grid'>";
echo "<div class='span12'>";
echo "<div class='span1'>";
echo "<label>Location:</label>";
echo "</div>";
echo "<div class='span11'>";
echo "<label id='labelAccordionLocation'>",
$row['Location'],"</label>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<div class='row-fluid show-grid'>";
echo "<div class='span12'>";
echo "<a id='select' class='btn'>Select</a>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
$group = $row['Name'];
}
}
}
?>
</div>
<div id="divDetails" style="display: none;">
<label>Name:</label>
<label id="labelName"></label><br />
<label>Location:</label>
<label id="labelLocation"></label><br />
<a id="close" class="btn">Close</a>
</div>
<script>
// Hide the accordion and show the hidden div
$('a.btn').click(function() {
$('#accordion2').hide();
$('#divDetails').show();
// Pass the label value from the accordion row to the hidden div label
$('#labelName').html($('.accordion-body.in .labelAccordionName').html());
$('#labelLocation').html($('.accordion-body.in .labelAccordionLocation').html());
});
// Hide the div and show the accordion again
$('#close').click(function() {
$('#accordion2').show();
$('#divDetails').hide();
});
// Only allows one row to be shown at a time
$('.accordion-toggle').click(function() {
var $acc = $('#accordion2');
$acc.on('show', '.collapse', function() {
$acc.find('.collapse.in').collapse('hide');
});
});
$(document).ready(function(){
// On dropdown change, pass in value to populate accordion/details
$('#dd').change(function() {
var r = $(this).val();
location.href = "test.php?src=" + r;
});
});
</script>
I did some searching on the jQuery site to try and figure this one out but unfortunately was unable to get it working. I'll do my best to give any additional information that is needed.
Edits
I changed the label's to use classes instead of id's. Although a great suggestion, I did not have to apply a new class 'activeAccordion'. Since the class 'in' is applied to the expanded row, I was able to use it for access as seen below. I also updated the jsFiddle and provided a link at the bottom.
$('a.btn').click(function() {
$('#accordion2').hide();
$('#divDetails').show();
$('#labelName').html($('.accordion-body.in .labelAccordionName').html());
$('#labelLocation').html($('.accordion-body.in .labelAccordionLocation').html());
});
Working jsFiddle
http://jsfiddle.net/N8JuQ/
You should consider escaping out of PHP in your if statement and only jump back in to echo the variables. Also read up on alternative syntax: http://php.net/manual/en/control-structures.alternative-syntax.php
while ($row = odbc_fetch_array($db)) {
if ($row['Name'] != $group){
?>
<div class='accordion-heading'>
<a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#", <?php echo $row['Number']; ?>,"'>
<button id='buttonAccordionToggle' data-target='#", <?php echo $row['Number']; ?>,"'>", <?php echo $row['Name']; ?>,"</button></a>
</div>
<div id='", <?php echo $row['Number']; ?>,"' class='accordion-body collapse'>
<div class='accordion-inner'>
...
...
...
<?php
}
?>
when generating html with php, as long as you are iterating be careful with IDs. Never generate same ID in a DOM, it messes things really bad. (ie. select, labelAccordionName, buttonAccordionToggle) I suggest using classes or generating unique IDs plus a generic class
you should have something like :
<div class="accordion" id="accordion2">
<?php
// SQL stuff here...
$group = null;
while ($row = odbc_fetch_array($db)) {
if ($row['Name'] != $group) {
echo "<div class='accordion-heading'>";
echo "<a class='accordion-toggle' data-toggle='collapse'
data-parent='#accordion2' href='#", $row['Number'],"'>
<button class='buttonAccordionToggle'
data-target='#", $row['Number'],"'>", $row['Name'],"</button></a>";
echo "</div>";
echo "<div id='", $row['Number'],"' class='accordion-body collapse'>";
echo "<div class='accordion-inner'>";
echo "<div class='control-group' style='min-height: 50px'>";
echo "<div class='row-fluid show-grid'>";
echo "<div class='span12'>";
echo "<div class='span1'>";
echo "<label>Name:</label>";
echo "</div>";
echo "<div class='span11'>";
echo "<label class='labelAccordionName'>",
$row['Name'],"</label>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<div class='row-fluid show-grid'>";
echo "<div class='span12'>";
echo "<div class='span1'>";
echo "<label>Location:</label>";
echo "</div>";
echo "<div class='span11'>";
echo "<label class='labelAccordionLocation'>",
$row['Location'],"</label>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<div class='row-fluid show-grid'>";
echo "<div class='span12'>";
echo "<a class='select btn'>Select</a>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
$group = $row['Name'];
}
}
}
?>
</div>
<div id="divDetails" style="display: none;">
<label>Name:</label>
<label id="labelName"></label><br />
<label>Location:</label>
<label id="labelLocation"></label><br />
<a id="close" class="btn">Close</a>
</div>
<script>
something like that, didn't check as you don't provided a jsfiddle. As for your data to retrieve correctly, I would suggest adding a class on active accordion-body then in your finds use this class to select the correct element :
$('.accordion-toggle').click(function() {
var $acc = $('#accordion2');
$('.activeAccordion').removeClass('activeAccordion');
$(''+$(this).next('.buttonAccordionToggle').data('target')).addClass('activeAccordion');
$acc.on('show', '.collapse', function() {
$acc.find('.collapse.in').collapse('hide');
});
});
then use this new class :
$('#labelName').html($('accordion-body.activeAccordion .labelAccordionName').html()));
$('#labelLocation').html($('accordion-body.activeAccordion .labelAccordionLocation').html()));

getting MySQL ID from URL to display information on page

I have a products page where 8 product images are in a list which is being populated by images stored in a MySQL database. The images all have associated ID's in which a price, product name, and description is also associated with the same ID.
The idea behind what I am trying to do is; When a user clicks on one of the 8 product images, they will be redirected to a "checkout" page which will display the same image, plus all the information that is also stored under that ID in the database.
As of right now, I have the checkout page URL including the ID of the image (url.com/checkout.php?id=1) and I was hoping to find a way to get all the information stored under that ID in the URL to be displayed where called on the page.
Here is my php code that displays the images in the list on the products page:
// Grab the data from our template table
$sql = "select * from templates";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<li>";
echo "<a class=\"caption\" href=\"purchase.php?id=\"" . $row['id'] . ">";
// Note that we are building our src string using the ID from the database
echo "<img src=\"http://URL-REMOVED.com/file_display.php?id=" . $row['id'] . "\" />";
echo "<span>";
echo "<big>" . $row['name'] . "</big>";
echo $row['description'];
echo "</span>";
echo "</a>";
echo "</li>";
}
Here is the php code that is supposed to gather the information of the clicked product (but doesn't):
if (isset($_GET['id']))
$id=$_GET['id'];
else
$id=1;
if (isset($_GET['action']))
$action=$_GET['action'];
else
$action="empty";
switch($action){
case "add":
if($_SESSION['cart'][$id])
$_SESSION['cart'][$id]++;
else
$_SESSION['cart'][$id]=1;
break;
case "remove":
if($_SESSION['cart'][$id])
{
$_SESSION['cart'][$id]--;
if($_SESSION['cart'][$id]==0)
unset($_SESSION['cart'][$id]);
}
break;
case "empty":
unset($_SESSION['cart']);
break;
}
//Display Cart
if(isset($_SESSION['cart'])) {
$total=0;
foreach($_SESSION['cart'] as $id => $x) {
$result=mysql_query("select image,name,price,description from templates WHERE id=$id");
$myrow=mysql_fetch_array($result);
$image=$myrow['image'];
$name=$myrow['name'];
$price=$myrow['price'];
$description=$myrow['description'];
}
}
And here is the actual HTML/PHP where the information is supposed to be displayed:
<a class="caption" href="checkout.php">
<img src="http://URL-REMOVED.com/file_display.php?id=<?php $myrow['id'] ?>"/>
<span>
<big>
<strong><?php $myrow['name'] ?></strong>
</big>
<div class="price"><?php $myrow['price'] ?></div>
</span>
</a>
</div>
<div id="info_form_container">
<div class="product_info">
<div class="control-group">
<strong>Template Name:</strong>
<?php $myrow['name'] ?>
</div>
<div class="control-group">
<strong>Template Description:</strong>
<?php $myrow['description'] ?>
</div>
<div class="control-group">
<strong>Template Price: </strong>
<?php $myrow['price'] ?>
</div>
</div>
I guess I'm not really sure if this is even the best method to take? But I definitely want to have the images stored in the database and I definitely want to call them using the ID...
How can I achieve this? Where am I wrong in my code?
EDIT: I do not think I understood your question the first time. Try using this to generate your list of products, updating the connection information. If this works, use the methods below to sanitize your variables and store your connection information elsewhere
<?php
$mysqli_connection = new mysqli("localhost", "username", "password", "database");
$sql = "SELECT * FROM templates";
$result = $mysqli_connection->query($sql);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
echo '<li>';
echo '<a href="purchase.php?id='.$id.'" class="caption">';
echo '<img src="http://URL-REMOVED.com/file_display.php?id='.$id.'" />';
echo '<span>';
echo '<big>'.$name.'</big>';
echo $description;
echo '</span>';
echo '</a>';
echo '</li>';
}
?>
OG Answer:
I think what you are doing is just fine.. It is the method I use (although mine seems a little neater). Run your PHP functions to query your MySQL database using the ID you get, and just start dumping the information you get into your site. To help with readability and cut down on spelling confusions, it might help to assign your $myrow['whatever'] results into variables to echo out, but that is more cosmetic to me than anything.
To fix up your MySQL things and use mysqli, try out the following:
$sql = "SELECT * FROM templates";
$result = $mysqli_connection->query($sql);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo "<li>";
echo "<a class=\"caption\" href=\"purchase.php?id=\"" . $row['id'] . ">";
// Note that we are building our src string using the ID from the database
echo "<img src=\"http://URL-REMOVED.com/file_display.php?id=" . $row['id'] . "\" />";
echo "<span>";
echo "<big>" . $row['name'] . "</big>";
echo $row['description'];
echo "</span>";
echo "</a>";
echo "</li>";
}
And try to sanitize your information using:
$my_stuff = mysqli_connection->real_escape_string($row['that_stuff']);
Also, you know you can use single quotes ('') around your echo statements if you want to, right? May make it easier that escaping all of the double quotes..
So in full, this is probably a rough example of what I would do but I would split it up into functions and maybe create some global variables (such as the connection itself):
<?php
$mysqli_connection = new mysqli("localhost", "username", "password", "database");
$sql = "SELECT * FROM templates WHERE id=$id";
$result = $mysqli_connection->query($sql);
// I'm assuming there is only one entry, so no while loop for me
$row = $result->fetch_array(MYSQLI_ASSOC);
$your_title = $mysqli_connection->real_escape_string($row['title']);
$path_to_image = $mysqli_connection->real_escape_string($row['image']);
$description = $mysqli_connection->real_escape_string($row['description']);
$price = $mysqli_connection->real_escape_string($row['price']);
?>
<html>
<head></head>
<body>
<h3><?php echo $your_title; ?></h3>
<img src="<?php echo $path_to_image; ?>" />
<ul>
<li>Description: <?php echo $description; ?></li>
<li>Price: <?php echo $price; ?></li>
<!-- etc..-->

Php foreach echo issue

I have this code which produces me a number which is equal to the number of id's i've got in my database of star rating system.
This code generates me a five star voting for each id i've got, but the problem is, it generates them all in a div, while i need them specifically in different div's. let's suppose i print out in a div information for each hostess i've got, i print out their photo and name with the following code:
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo "<div id='photo'>";
echo "<div id='picture'>";
echo "<div id='scotch'><img src='images/Scotch.png'></div>";
echo "<td> <img src=foto/photo1/".$row['photo'] . "></td>";
echo "</div>";
echo "<div id='text'>";
echo '<td>'. $row['first_name_en']." ". $row['family_name_en']."</td>";
echo "</div>";
echo "</div>";
echo "<div id='photo2'>";
echo "<div id='picture'>";
echo "<div id='notes'>";
echo '<form action="index.php" method="post" >';
echo "<label>Notes</label></br><textarea>".$row['courrent_occupation'] . "</textarea></br>";
echo '<input type="submit" value="edit" name="edit"></div>';
echo "</div>";
echo "<div id='notes'>";
echo "<label>profile</label></br><textarea>".$row['profile_en'] . "</textarea>";
echo "</div>";
echo "</div>";
}
?>
</div>
Now, i've got this other php which generates me all the star ratings for all hostess id's
<?php
// include update.php
include_once 'update.php';
// get all data from tabel
$arr_star = fetchStar();
?>
<?php
// start looping datas
foreach($arr_star as $star){ ?>
<h2>Star Rater - <?php echo $star['id'];?></h2>
<ul class='star-rating' id="star-rating-<?php echo $star['id'];?>">
<?php /* getRating($id) is to generate current rating */?>
<li class="current-rating" id="current-rating-<?php echo $star['id'];?>" style="width:<?php echo getRating($star['id'])?>%"><!-- will show current rating --></li>
<?php
/* we need to generate 'id' for star rating.. this 'id' will identify which data to execute */
/* we will pass it in ajax later */
?>
<span class="ratelinks" id="<?php echo $star['id'];?>">
<li>1</li>
<li>1.5</li>
<li>2</li>
<li>2.5</li>
<li>3</li>
<li>3.5</li>
<li>4</li>
<li>4.5</li>
<li>5</li>
</span>
</ul>
<?php } ?>
What i need is to assign each hostess profile i print their system rating.
I try to insert the foreach inside the first script but it then shows me just one profile, not all profiles.
The fetchstar() code is:
function fetchStar(){
$sql = "select * from `hostess`";
$result=#mysql_query($sql);
while($rs = #mysql_fetch_array($result,MYSQL_ASSOC)){
$arr_data[] = $rs;
}
return $arr_data;
}
First, you probably shouldn't use SELECT *. That aside I would combine the two queries you have to return a multidimensional array with MySQL and then use nested for each loops to echo out the data you want.
Someone answered a similar question for me here.
Looping through MySQL left join in php vs. 2 separate queries
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
if ($lastID <> $row['id']) {
$lastID = $row['id'];
$hostess[$lastID] = array('id' => $row['id'],
'first_name_en' => $row['first_name_en'],
etc
'arr_star' => array() );
}
$hostess[$lastID]['arr_star'][] = array('star_id' => $row['star_id'] etc);
}
Then you would use nested for each statements
for each($row as $rows){
//echo your hostess information
for each ($arr_star as $star){
//echo your star rating information
}
}

Categories