Set variable depending on MySQL row - php

I have a MySQL table that has various entries, some with video links, and some without. Let's call this row "vid" for now. I would like, if the row has a link (or any text at all), to set the link equal to the $pc162v variable, and if the row has no content for "vid" to set the variable to be blank.
Here's the variable declaration:
$pc162v = "";
$v162 = '<center><embed width="420" height="236" src="'.$pc162v.'" type="application/x-shockwave-flash"></embed></center><hr>';
Further down in the code, all under an "if" statement:
} else {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row[7] != "") {
$pc162vid = $row[7];
}
else {
$vidspot162 = '';
}
The area for the video, even though the PHP is being pointed to the correct row, is blank. Any help/ideas is appreciated!

Related

Output Component With A While Loop Even If The Component Content Is Empty - PHP

I have a while loop that outputs three images onto an image preview board. This aspect is all working OK. I would like it so that if a preview board has no allocated images it still outputs the board component, but displays a message such as 'Add images to this board'.
In the code below, if the board preview component (the <figure>element) is empty, it currently outputs an unwanted single empty <img> tag. I thought I could fix this by changing this code block:
if ($imgcount < 3) {
echo "
<img src='{$dbImageFile}'>
";
}
to this:
// only allow 3 images per board
if ($imgcount < 3 && isset($dbImageFile)) {
echo "
<img src='{$dbImageFile}'>
";
}
// echo empty string if no image for this board
if ($imgcount < 3 && !isset($dbImageFile)) {
echo "";
}
...which I thought would output an empty string instead of the unwanted single <img> tag if the board has no images allocated to it. This single image tag is missing the filename from its path (although I obviously want to stop this image tag being outputted completely)
And then at the end of the while loop, add the following message when there are no images (this is currently commented out in the main code)
if ($imgcount == 0 ) {
echo "Add Images To This board";
}
In the MySQL code the boards_images table is a linking/pivot table that holds the board id and a related image id for that board.
<?php
$s = "SELECT boards.board_name, boards.board_id, images.filename
FROM boards
LEFT JOIN boards_images on boards_images.board_id = boards.board_id
LEFT JOIN images on boards_images.image_id = images.image_id
WHERE boards.user_id = :user_id
ORDER BY boards.board_id";
$stmt = $connection->prepare($s);
$stmt -> execute([
':user_id' => $db_id // $_SESSION login variable
]);
$dbBoardname_last = '';
$imgcount = 0;
while ($row = $stmt->fetch()) {
$dbBoardId = htmlspecialchars($row['board_id']);
$dbBoardname = htmlspecialchars($row['board_name']);
$dbImageFile = htmlspecialchars($row['filename']);
// close the previousboard component <figure>
if($dbBoardname_last != '' && $dbBoardname != $dbBoardname_last) {
echo "
</figure>
";
}
//if the board name is the different to the previous one add the opening component tag
if($dbBoardname != $dbBoardname_last) {
//reset the image count for new boards
$imgcount = 0;
// output opening board component <figure>
echo "
<figure class='board-component'>
<h2>{$dbBoardname}</h2>
";
}
// only allow 3 images per board
if ($imgcount < 3) {
echo "
<img src='{$dbImageFile}'>
";
}
$imgcount+=1;
//record the last board_name to check if a new board element should be created
$dbBoardname_last = $dbBoardname;
// *** IF NO IMAGES ARE PRESENT ECHO THE 'ADD IMAGES' MESSAGE ***
// if ($imgcount == 0 ) {
// echo "Add Images To this board";
// }
}
// close the last board component element
if ($dbBoardname_last != '') {
echo "
</figure>
";
}
?>
When a board has no images linked to it, MySQL populates the filename value with NULL. And, when a NULL value is passed to the PHP htmlspecialchars() function, it returns an empty string.
// when "filename" from the database is NULL, $dbImageFile is assigned an empty string.
$dbImageFile = htmlspecialchars($row['filename']);
Also PHP isset() function returns true when it is passed a variable that contains an empty string. Therefore the condition if ($imgcount < 3 && isset($dbImageFile)) { writes the image tag when there is no image linked to the board.
When using htmlspecialchars() you'll never get a NULL, and MySQL always returns "filename" as a declared variable, even when it is assigned NULL. That's why isset() does not do what you expect with $dbImageFile.
Either use the value, possibly containing NULL, returned in the MySQL results set. $row['filename']:
// only allow 3 images per board
if ($imgcount < 3 && isset($row['filename'])) {
echo "
<img src='{$dbImageFile}'>
";
}
...or, check for an empty string, "" !== $dbImageFile:
// only allow 3 images per board
if ($imgcount < 3 && "" !== $dbImageFile) {
echo "
<img src='{$dbImageFile}'>
";
}
This is all you need. You don't need the second if condition with another "less than 3 images written to the board" check, and if the $dbImageFile is not set: !isset($dbImageFile):
$dbImageFile in your code will always return true when passed to isset() (is set).
$dbImageFile in your code will always return false when passed to !isset() (is not set).
This is kind of tricky problem, because your query contains duplicates, in your case I would suggest to map the records at first and then looping them and print the HTML code
<?php
$boards = [];
while ($row = $stmt->fetch()) {
$boards[$row['board_id']] = $boards[$row['board_id']] ?? [];
$boards[$row['board_id']]['name'] = $row['board_name'];
$boards[$row['board_id']]['images'] = $boards[$row['board_id']]['images'] ?? [];
$boards[$row['board_id']]['images'][] = $row['filename'];
}
foreach ($boards as $board_id => $board) {
echo '<figure>';
echo $board['name'];
$images_length = count($board['images']);
for ($i = 0; $i < min($images_length, 3); $i++) {
echo "<img src='{$board['images'][$i]}'>";
}
if ($images_length === 0) {
echo "Add images to this board";
}
echo '</figure>';
}

Show different image depending on value in variable

just want to make sure I'm going in the right direction with this. I have an image which I want to be replaced/changed if the value of a variable is either 0/1. So here is the code from the guy doing the server side stuff.
<?php
//Requires mysql_connect to create the connection
$link_state = 0;
//If you so wish you don't have to check for a connection, but may be a good idea leave this in.
if ($mysql_connection['connected'] == true) {
$result = mysql_query("SELECT * FROM link");
//The bit we are looking for should be the first row, and we should only get one row
$count = mysql_num_rows($result);
if ($count <= 0) {
//Interesting...
$mysql_error['error'] = true;
$mysql_error['description'] = "ERROR: No rows were returned from table 'link'";
} else {
//We should be ok to continue
if ($count > 1) {
$mysql_error['error'] = true;
$mysql_error['description'] = "WARNING: Found more than one row in 'link' table!";
}
$row = mysql_fetch_array($result);
$link_state = intval($row['state']);
}
} else {
$mysql_error['error'] = true;
$mysql_error['description'] = "ERROR: No mysql connection!";
}
/*
After the completion of this page, $link_state will be one of two things:
* 0 = offline
* 1 = online
Throws to $mysql_error:
1 Warning
2 Errors
*/
?>
Okay, so I'm assuming by that little bit of code I will then have a value of either 0 or 1 in $link_state.
So from this can I then just do a simple inline script like this to get my relevant image?
<img src="img/<?=($link_state=="0"?"off.jpg":($link_state=="1"?"on.jpg":))?>" />
Any insight would be great :)
Thanks in advance.
try this
<?php $img = ($link_state == "0") ? "off.jpg" : "on.jpg"; ?>
<img src="./img/<?php echo $img; ?>" />
also use mysqli_* since mysql_* is depreciated.

PHP getimagesize, Mysql fetch from DB and update field

I've been a lot around this site the last couple of days, and found a lot of useful tips for a newbie to php as I am (this is my second day :) ) Therefore I'll sure hope you gurus can help me finishing this script.
What do I have:
I have this table within my Mysql:
------------------------------![Sql Tabels][1]
----------------------
Would should it do:
The script have to get some table rows where the "diemensions" field is emty IS NULL
Now the script have to find the image size and spit it out in this format widthxheight the x between the width and height is important.
Where the image is not to be grabt, it should just pass by, and take the next one.
When it's done:
It have grabt the image size and updated the "dimensions" field in the DB
Sources for my code:
How to determine the picture size, then selectively insert into the database? php
Update MySql Field (if field is not empty, go to next one)
http://dk1.php.net/manual/en/function.getimagesize.php
The PHP it self
<pre><code>
<?php
# first we check, if gd is loaded and supports all needed imagetypes
function gd_get_info() {
if (extension_loaded('gd') and
imagetypes() & IMG_PNG and
imagetypes() & IMG_GIF and
imagetypes() & IMG_JPG and
imagetypes() & IMG_WBMP) {
return true;
} else {
return false;
}
}
$username = "";
$password = "";
$database = "";
$db_hostname = "";
mysql_connect("$db_hostname","$username","$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM tx_gallery_previews WHERE dimensions IS NULL ORDER BY gallery_id ASC LIMIT $startrow, 10") or die(mysql_error());
// store the record of the "example" table into $row
while($row = mysql_fetch_array($result)){
//$row = mysql_fetch_array($result))
$pid = $row['preview_id'];
$gid = $row['gallery_id'];
$imgfile = $row['preview_url'];
$dimens = $row['dimensions'];
/*
echo $row['gallery_id'];
echo $row['preview_url']. "\r\n<br />"; */
extract($row);
//print $pid. " ".$imgfile." ";
//print "".$dimens."<br />";
$blah = getimagesize("$imgfile");
$type = $blah['mime'];
$width = $blah[0];
$height = $blah[1];
if (isset($width)) {
echo $pid. " ".$imgfile." ".$width. "x".$height. "\n"."<br />";
mysql_query("UPDATE into tx_gallery_previews (preview_id,gallery_id,preview_url,dimensions) VALUES ($pid,$gid,$imgfile,$width."x".$height)
ON DUPLICATE KEY UPDATE dimensions=VALUES('"$width."x".$height"')");
}
else{ echo "$pid <img src=\"$imgfile\" width=\"90\">Image not found"."<br />"; }
}
// close connection
mysql_close($connection);
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous ';
//now this is the link..
echo 'Next';
?>
</pre></code>
Seen but couldn't make it work
http://dk1.php.net/manual/en/function.getimagesize.php
Post by "james dot relyea at zifiniti dot com 07-Feb-2009 08:49"
But seems to be the right ideer for my script.
XXXXXXXXXXXXXXXXX
When you answer this topic, please explane wich part does what.
Best Regards
Joakim

MYSQLI Returns only 1 value while there's 2

I've started making a Video script that loads the videos using MySql and I am using Mysqli.
However, There's 2 Rows that it should post, but it only post the second none, not the first one.
It loads the results using "Brand" so if there's 2 rows named "Test", it only loads the second one, but not the first one.
So, what is causing this? I've tried with 3 rows, and it did not include the first row.
Code
<?php
{ /* Global Data */
ini_set('display_errors', 0);
ini_set('error_reporting', -0);
$GetPath = $_GET['b'];
$SqlUser = "root";
$SqlPass = "**Private**";
$SqlHost = "localhost";
$SqlData = "heisteknikk";
}
{ /* Mysql Connect */
$Sql = new mysqli($SqlHost, $SqlUser, $SqlPass, $SqlData);
if ($Sql->connect_error) { die("Sorry, Could not connect (".$Sql->connect_errno.") ".$Sql->connect_error);}
}
{ /* Test */
$Brand = $Sql->real_escape_string($GetPath);
$SqlData = "SELECT * FROM videos WHERE Brand = '".$Brand."'";
$SqlQuery = $Sql->query($SqlData);
if (!$SqlQuery) {
echo $Sql->error;
}
if ($SqlQuery->num_rows == 0) {
die("Nothing was found");
}
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
echo "
<tr><td>".$Heis['Brand']."</td><td>".$Heis['Name']."</td><td>".$Heis['Location']."
";
}
echo "</table>";
$Sql->close();
}
?>
This line causes the bug:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
With this line you effectively throw out the first row of the result set, as you don't process $Data at all in the code below. Just remove it, and your script should work fine (I assume that closing </td></tr> sequence was lost when pasting the code, am I right?)
Comment out (or better yet, remove) this line:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
It is grabbing the first row...then you aren't doing anything with $Data and then grabbing the second (and consecutive rows) for display in your while loop. Commenting out that line above will make your loop grab and display them starting at the first one.
In your code
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
you're fetching a row (with fetch_array), throwing it away and then fetching another row (with fetch_assoc). That's probably why you're only seeing one row instead of two

setting a link on a while loop php

$query = mysql_query("SELECT * FROM mailtbl WHERE fromuser = '$adminsess' AND sent = '1'");
echo "To Subject Date View message";
while($fetch = mysql_fetch_assoc($query)) {
$mid = $fetch['mid'];
$to = $fetch['touser'];
$subject2 = $fetch['subject'];
$message2 = $fetch['message'];
$date2 = $fetch['datesent'];
$rand = $fetch['rand'];
$view = "<a href = 'messages.php?mode=".$sent."&view=".$rand."'>View message</a>";
echo "$to$subject2$date2$view";
}
echo "</table>";
if (isset($view)) {
$viewget = $_GET['view'];
if ($viewget== $rand) {
echo "hi";
echo "$message2";
}
}
The $view there suppose to open the content of each message. The main problem is, if I have multiple values in the table, after clicking the link in each row in the table, the only link that is functioning is in the last row. The previous rows in the table with links doesn't show the content of the message (which is echo "hi" & echo "$message2";).
What exactly is wrong with my code? thanks.
Your code to display the message is outside the while loop. If you want it to run for every message, then put it in the loop that is iterating over every message.
The problem is that $rand is not set inside the isset($view) check. $rand still contains the last value from the while loop above, so only the last $viewget/$rand will work.
My guess is that messages.php shows all available messages (the message list) and if clicked on one message, the message list and that selected message.
So first, before the while loop, you fetch the message identifier of the message to be shown:
$ViewRequested = isset($_GET['view']) ? $_GET['view'] : -1;
$ViewRequestedData = NULL;
Next, inside the while loop, you check if the user is allowed to view the selected message, and remember the record:
if ($rand == $ViewRequested) {
$ViewRequestedData = $fetch;
}
Finally, after the while loop, you check whether there is a valid message requested:
if (is_array($ViewRequestedData) {
echo $ViewRequestedData['message2'];
}

Categories