PHP getimagesize, Mysql fetch from DB and update field - php

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

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>';
}

PHP Recursion -- Increment query variables

I have a database where each row contains a unique userid number, and a referralid number that links them to the person that referred them to the site. I am trying to create a recursive function that will search the database as long as it continues to find users, and perform several calculations as it goes. Below is what I have so far - I am getting stuck on trying to create incrementing query variables - PLEASE HELP!
function findrepsloop($refidnum, $num){
echo "FINDREPSLOOP STARTED<br><br>";
if(strlen($refidnum) > 0){
echo "FIRST STRLEN IF LOOP PASSED: $refidnum<br><br>";
$totalreps++;
$query{$num} = "SELECT * FROM user WHERE (refidnum = '$refidnum' && active = 'YES') ";
$result{$num} = mysql_query($query{$num});
$line{$num} = mysql_fetch_array($result{$num}, MYSQL_NUM);
$total{$num} = mysql_num_rows($result{$num});
echo "QUERY $num found $total{$num} rows in the database. LINE 0: '$line{$num}[0]<br><br>";
$totaltemp = 0;
if($total{$num} > 2){ $totaltemp = $total{$num} / 3; $totaltemp = floor($totaltemp); }else{}
$numberofthrees = $numberofthrees + $totaltemp;
while(strlen($line{$num}[0]) > 0){
$refidnum = $line{$num}[0];
$num++;
findrepsloop($refidnum, $num);
$line{$num} = mysql_fetch_array($result{$num}, MYSQL_NUM);
}
}else{
}
}

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.

Mystified about making a PHP double-query dynamic list work. Using PHP 5.3.5

I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....

If fetched data from MySql is smaller than *number*, show this, else show something else?

Hi Masters of Web Programing.
I've got this code:
<?PHP
$db_user = 'user';
$db_pass = 'password';
$db_name = 'dbname';
$db_host = 'localhost';
if(mysql_connect($db_host,$db_user,$db_pass)) {
mysql_select_db($db_name);
mysql_query("CREATE TABLE IF NOT EXISTS smsads(id bigint unsigned primary key auto_increment, link varchar(255), fromnum varchar(60))");
$res = mysql_query("SELECT * FROM smsads ORDER BY id DESC LIMIT 36");
while($row = mysql_fetch_object($res)) {
if ($res>=36){
$http_link = $row->link;
$root_link = strpos($http_link, '/');
if ($root_link !== false) {
$before = substr($http_link, 0, $root_link);
}
echo "<div id=\"banner\"><img src=\"http://{$http_link}\" /></div>";
}
else {
echo $res . "<div id=\"banner\"></div>";
}
}
}
?>
</div>
As we can see, the number of fetched rows are limited to 36. How to make if rows are smaller than 36, to show the existing ones plus adding something else for each one until 36?
For example this is a script for pixel advertisement, and I want to visualize the existing pixels (for example, I have 20 inserted pixels), and to show empty boxes into other places that are empty (total 36 places - 20 already placed items = 16 empty places) until the count reaches total 36 boxes.
As you can see, I tried with "If", "else", but it always shows only empty boxes (becouse I don't know how to tell it to show RESULTS + empty boxes)...
Rewrite everything into a for loop, it also makes everything a bit easier to understand:
for($cnt = 0; $cnt < 36; $cnt++){
if($row = mysql_fetch_object($res)){
// In here you should have the code for the boxes to be filled.
$http_link = $row->link;
$root_link = strpos($http_link, '/');
if ($root_link !== false) {
$before = substr($http_link, 0, $root_link);
}
echo "<div id=\"banner\"><img src=\"http://{$http_link}\" /></div>";
}else{
// In here you should have the code for the empty boxes
echo "<div id=\"banner\"></div>";
}
}
This will always iterate through the loop 36 times, those times it will find a row it will print the row, otherwise it will print the empty banner tag.
Use mysql_num_rows:
if (mysql_num_rows($res) >= 36) {
// ...
}
Have you tested the code that executes if the if statement is true?

Categories