Display query in a div or custom location? - php

How could I have my database connection information at the top of my page but have the query separate from the code but still related so that I could have the print or echo displaying the retrieved images in a Div that I could place anywhere on my site?
<?php
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$q = "SELECT badge1 FROM user_badges WHERE username='{$_SESSION['username']}' LIMIT 1";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$badge1 = $row['badge1'];
if($badge1 == "unlocked") {
print "image if user has unlocked the badge";
} else {
print "image if user hasn't unlocked the badge";
}
?>
I would like to have the above if and else statements placed in a div so I could position the images printed from the query anywhere on my site. Is this possible?

A couple of ways. Here is one example:
<?php
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$q = "SELECT badge1 FROM user_badges WHERE username='{$_SESSION['username']}' LIMIT 1";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$badge1 = $row['badge1'];
?>
//Break out of PHP and add any HTML elements you want
<div id="whatever">
<?php
if($badge1 == "unlocked") {
print "image if user has unlocked the badge";
} else {
print "image if user hasn't unlocked the badge";
}
?>
</div>
p.s. Check your PDO. It's mixed with old MySQL_ stuff

Related

passed variable returns empty in url on target page

I am going out of my mind as it is. I am trying to pass a variable from a page that shows all albums thumbnail image and name to a page that will display all the pictures in that gallery using that passed variable, but the variable is empty in the url on the target page. I have seen similar cases on the web and on this site and I've applied the suggestions but it's still the same. Here is the code that lists the thumbnail and passes the variable(id).
<?php
include ("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
$albums = mysqli_query($conn,"SELECT * FROM albums");
if (mysqli_num_rows($albums) == 0) {
echo "You have no album to display. Please upload an album using the form above to get started. ";
}
else{
echo "Albums created so far:<br><br>";
echo "<table rows = '4'><tr>";
while ($thumb = mysqli_fetch_array($albums)) {
echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
}
echo "</tr></table>";
}
?>
The code for getting the passed variable is as follows:
<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
$album_id = $_GET['id'];
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn,$pic);
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
}
else{
echo "Pictures in the gallery:<br><br>";
while ($result = mysqli_fetch_assoc($picQuery)) {
echo "<img src='".$result['photo_path']."'/>";
}
}
}
?>
Please help as i have spent the last two days trying to get it right.
First, your's code is weak against sql injections:
$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
Use either $album_id = intval($_GET['id']) or prepared statements functionality.
Second, add debug lines to your code, like:
<?php
include("config.php");
if (isset($_GET['id'])) {
$album_id = intval($_GET['id']);
var_dump($album_id); // should print actual passed id
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
var_dump($conn _id); // should print conn resource value
$db = mysqli_select_db($conn, dbname);
var_dump($db); // should print 'true' if db select is ok
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn, $pic);
var_dump($picQuery); // should print query resource value
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
} else {
echo "Pictures in the gallery:<br><br>";
while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
var_dump($result ); // should print fetched assoc array
echo "<img src='".$result['photo_path']."'/>";
}
}
}
Notice $album_id = intval($_GET['id']) and while (($result = mysqli_fetch_assoc($picQuery)) !== false) parts
Then follow link view.php?id=<existing-album-id> and observe debug result. On which step debug output differs from expected - there problem is.

execute mysql DELETE query on click

i'm kind of a new player in php and sql field.
i'm trying to delete identity from my persons table when clicking on the remove link (or button)
can somebody tell me what am i doing wrong?
this is my php code:
<?php
$db = new DB();
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
$sql ="SELECT f_name, phone, c.id as idc
FROM contacts as c
WHERE c.cg_id = '$cg_id'";
$result = $db->mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article>";
if(isset($_POST['idc'])){
$idco = $_POST['idc'];
$removeQuery = "DELETE FROM contacts as c WHERE id=".$idco." ";
$resultt = mysql_query($removeQuery);
if($resultt) {
header('Location: '.$_SERVER['REQUEST_URI']);
}
echo "<script>window.location.reload(true);</script>";
}
}
}else {
echo "Please edit senior profile for monitoring!";
}
?>
Try this (obviously replacing "localhost", "dbuser", "dbpassword" and "database_name" with the details for your mysql server and database):
<?php
$db = new mysqli("localhost","dbuser","dbpassword","database_name");
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
// I've moved the deletion code to BEFORE the select query, otherwise the
// query will be shown including the to-be-deleted data and it is then deleted after it is displayed
if(isset($_GET["del"])){ // <--- this was $_POST["del"] which would have been unset
$idc = $_GET["del"];
if($db->query("DELETE FROM contacts WHERE id=$idc")){
echo "deleted";
} else {
echo "fail";
}
}
$sql ="SELECT photo, f_name, phone, street, street_num, city, l_name, c.id as idc FROM contacts as c, address as a WHERE c.cg_id = '$cg_id' and a.id = c.address_id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<article class='contact5 lior'>";
echo "<img class='CSImage' src='" .$row["photo"]."'>";
echo "<section class='generalFormTextW nameCPosition'> " .$row["f_name"]." ".$row["l_name"]."<br></section>";
echo "<section class='generalFormTextW phoneCPosition'> " .$row["phone"]."<br></section>";
echo "<section class='generalFormTextB addressCPosition'>".$row["city"].", <br> ".$row["street"]." ".$row["street_num"]. "<br></section>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article></article>";
}
}
?>
Notice that I'm changing the way you're using mysqli so that you are using it directly rather than as a member of the DB object which is the way I've seen it used elsewhere - It looks to me as if you don't actually open the database connection (although maybe you just didn't include it because it showed your password?)
**EDIT: I've changed $_POST["del"] to $_GET["del"] -- because you are setting del in a url ("contacts2.php?del=") this will be GET not POST.
**EDIT: I've moved the deletion code so that it fixes the problem where you have to refresh the page to see the data with the record deleted - previously the information was shown and THEN deleted, we want to delete THEN show.

PHP if in POST load only the first if

I have this code :
if(isset($_POST['remove'])){
$con = mysqli_connect(".","","","");
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
It is working, but I want it to do something like this
if(isset($_POST['remove'])){
$con = mysqli_connect("","","","");
while($row = mysqli_fetch_assoc($q)){
if($row['picture'] == ""){
echo "<div class='notemarg'> No pictures to delete</div>";
} else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
}
This means that the picture from database will be removed only if there IS any picture.. if not, then it will display that message "No pictures to delete" ... but it does not work.. it still shows that error message that there is no picture even though there is no blank row in database and so it does not delete the information in row either...
Where is problem?
BTW: first code works fine... and it works even if there is nothing in database so it kinda does not make sense that the "profile picture has been removed." is being displayed...
Try this instead:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con, "SELECT picutre FROM members where username = '". $_SESSION['username']. "'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
You need the mysqli_query statement:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con,"SELECT IFNULL(picture,'') AS picture
FROM members
WHERE username = '".$_SESSION['username']."'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}

PHP mySQL search script for website

I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !

MySQL PHP record checking

im having a simple mysql/php problem. so i am adding in Image titles for my website, and the code is displayed below. It works, but when you dont put a image, it shows up as blank. I need it to show up as 'No image title' (bc i will use this for image description to). It basically gets the image name, then takes the title from that row.
So how do i do it? :/ im still very new to PHP.
<?php
if (isset($imgtitleset))
{
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result))
{
$imgtitle= $row["image_title"];
echo "$imgtitle";
}
}
else {
echo 'no image title';
}
?>
Change the while loop like so:
while ($row = mysql_fetch_array($result)) {
$imgtitle= $row["image_title"];
if($imgtitle != '') {
echo $imgtitle;
} else {
echo 'no image title';
}
}
Also, I'm not sure what the $imgtitleset variable is for, but you can probably get rid of the if statement checking to see whether it's set.
Edit: the whole thing should probably look like this:
<?php
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result)) {
$imgtitle= $row["image_title"];
if($imgtitle != '') {
echo $imgtitle;
} else {
echo 'no image title';
}
}
?>
This all depends on what $imgtitleset is equal to. It is clearly set against something:
while ($row = mysql_fetch_array($result)) {
$imgtitle = $row["image_title"];
if (isset($imgtitle))
echo "$imgtitle";
else
echo 'no image title';
}
This would mean if nothing was found in the database then it will echo the no image title. However like I said, this could depend on what $imgtitleset is, maybe post the code for that?
If you only expect the select to return a single row, then use if rather than while and return the error on else:
<?php
if (isset($imgtitleset))
{
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
if ($row = mysql_fetch_array($result))
{
$imgtitle= $row["image_title"];
echo "$imgtitle";
}
else {
echo 'no image title';
}
}
?>

Categories