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.
Related
This question already has an answer here:
echo image according to a condition
(1 answer)
Closed 6 years ago.
I have this query :
$q4 = "SELECT TOP 5 b.BadgeName, b.BadgeImage FROM BadgeImageTable AS b
INNER JOIN employee_badge AS e
ON e.badge_id = b.BadgeID
WHERE e.employee_id = 2164
ORDER BY e.earned_on DESC ";
$stmt3=sqlsrv_query($conn,$q4);
if($stmt3==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
the query returns this :
Now in my php, i am trying to echo any three random images from the 'BadgeImage' column,if the query gives more than 3 rows of data.Else,if the query gives 2 rows,display only 2 images,if 1 row,display only 1 'badgeImage' and so on.
PHP Code that I tried and which is not giving the correct result :
<div class="badgesize">
<?php
if($count = sqlsrv_num_rows($stmt3) > 0){
while($recentBadge = sqlsrv_fetch_array($stmt3)){
$result[] = $recentBadge;
}
if($count > 3){
foreach(array_rand($result, 3) as $val){
$data[] = $result[$val];
}
$result = $data;
}
foreach($result as $recentBadge){
echo $recentBadge['BadgeName'], '<img src="'.$badgerecent['BadgeImage'].'">';
}
} else {
echo 'no results';
}
?>
</div>
When I run the above PHP it is giving 'no result' inh the UI i.e "it is not running the if statement' and directly going to the else part of the PHP.
This shouldnot happen as the query fetches 5 rows of data as shown in above picture.
When I try to echo simply (using below code) without the above condition,I am able to do so without any issue.
<img src="<?php echo "".($recentBadge['BadgeImage']).""; ?>" >
I am using PHP 5.5.38 and sql server 2012
Change the following:
if($count = sqlsrv_num_rows($stmt3) > 0){
to
$count = sqlsrv_num_rows($stmt3); // getting the record count
if($count > 0){ // checking if there is some rows present or not
while($recentBadge = sqlsrv_fetch_array($stmt3)){
// your code
}
}
and one more thing do not put full path of the image in badgeImage column as this will create problem when you move code from local to server. Keep only path of image folder and image name.
Apparently sqlsrv_num_rows() does not return an expected result which is explained here
Alternatively you can use that fix or you can use the following code:
if(sqlsrv_has_rows($stmt3)){
while( $row = sqlsrv_fetch_array($stmt3, SQLSRV_FETCH_ASSOC) ) {
$recentBadge[] = $row;
}
if(count($recentBadge) > 3){
foreach(array_rand($recentBadge, 3) as $key){
$data[] = $recentBadge[$key];
}
$recentBadge = $data;
}
} else {
$recentBadge = [];
}
foreach($result as $recentBadge){
echo $recentBadge['BadgeName'], '<img src="'.$badgerecent['BadgeImage'].'">';
}
This way we're checking if there are found rows instead, is so, store them all in an array and count the size of the array instead.
replace
if($count = sqlsrv_num_rows($stmt3) > 0){
with
$count = sqlsrv_num_rows($stmt3);
if($count > 0){
I've stumbled upon a simple MySQL error, and it seems my attempts of fixing it are effortless. The problem, it's not counting.
Before I go further, I know that mysql_* is Deprecated, and that I shouldn't use it. I should use mysqli_* or PDO.
This is my Query, and yes, the echo is just for testing.
$ms_sql = mysql_query("SELECT * FROM mijnsp WHERE sp_username = '".$user['username']."'");
while ($mijnspusers = mysql_fetch_assoc($ms_sql)) {
$ms_count = mysql_num_rows($ms_sql);
if($ms_count <= 0){
echo "Result is empty";
}else{
echo $mijnspusers['new_username'];
}
I've tried to change the IF, but with no effect;
if($ms_count <= "0"){
or, like this
if($ms_count <= '0'){
Thank you in advance,
Pascal
Call
$ms_count = mysql_num_rows($ms_sql);
before the while() loop.
You should do the mysql_num_rows() before going into the loop. If the num is 0, then you'll never run the loop to begin with.
Your code should be:
$ms_sql = mysql_query("SELECT * FROM mijnsp WHERE sp_username = '".$user['username']."'");
$ms_count = mysql_num_rows($ms_sql);
if($ms_count == 0){
echo "Result is empty";
}else{
while ($mijnspusers = mysql_fetch_assoc($ms_sql)) {
echo $mijnspusers['new_username'];
}
}`
I am trying to create an admin notification system where on my database table named 'siteconfig' I have a row called setting='adminalerts' in this row will be certain alert columns such as:
nauseralert (non-activated user alert)
0 or 1
mmsitealert (maintenance mode site alert)
0 or 1
and so on...
I am trying to code something that will count the number of 0's or 1's in a row and display the value as a number. So if both of the above are set to 1, the value would be (2) and if there are only 1 alerts active it would be (1). If no alerts are active then it would show as (0) etc... Here is the code I have attempted to try but it doesn't seem to work? Was hoping for a little help here! Thanks!
<?
$sitealerts = mysql_query("SELECT * FROM siteconfig WHERE setting='adminalerts'");
$adminalerts = mysql_num_rows($sitealerts);
if ($nonactivated < 0){
echo 'Admin Alerts';
} else {
echo 'No Alerts';
}
echo $adminalerts;
?>
I know this is probably totally wrong, but pretty new to this stuff and have tried to find about it online but not too sure I really understand how to do this?
You have to access the columns to calculate the right value:
$sitealerts = mysql_query("SELECT * FROM siteconfig WHERE setting='adminalerts'");
//if the query was OK
if($sitealerts) {
//loop through all result rows
while(FALSE !== ($row = mysql_fetch_assoc($sitealerts))) {
//do the calculation
$count = 0;
$count += intval($row['nauseralert']);
$count += intval($row['mmsitealert']);
if($count > 0) {
print $count;
}
print '<br />';
}
mysql_free_result($sitealerts);
}
mysql is dprecated in php 5.5 http://php.net/manual/en/changelog.mysql.php
it is better to use mysqli.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// checking connection
if (mysqli_connect_errno()) {
exit();
}
if ($result = $mysqli->query("SELECT (nauseralert+mmsitealert) as alerts_count FROM siteconfig WHERE setting='adminalerts'")) {
while ($row = $result->fetch_row()) {
if($row['alerts_count'])
echo $row['alerts_count'];
else echo ' ';
}
$result->close();
}
$mysqli->close();
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
I have a code like this
<?php
$getLeftSide = 'select * from leftmenu';
$result = $db -> query ($getLeftSide) or die ("$db->error");
if ($result) {
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
}
?>
I need to echo this line one time
echo "<div class='left_main_cat'>Web and Design</div>";
of course it's under the while loop so it print it self many times
is there is a why to solve this and print this line one time only.
As Ben suggests, the easiest and clearest solution is to use a boolean check variable:
$catFound = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
// We only want this category printed for the first category,
// if it exists.
if(!$catFound) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
$catFound = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Although it seems better to use a boolean variable and a comment to make clear your intent.
Ugly, but I'm not that good at PHP yet!
$has_printed = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
if(!$has_printed){
echo "<div class='left_main_cat'>Web and Desigen</div>";
$has_printed = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Simple solution: Add another boolean variable with default value false Then just check if false, print your text and set it true.
adding a boolean or check variable or any kind of conditional inside of a loop is a very bad idea imho, i NEVER do it. every time you swing through the loop, the condition has to be checked. it's like a badly written switch/case.
figure out a way to do it before the loop.
unroll the loops, most people do it to save space but most compilers will unroll them anyway for optimization
stick it before the loop
find a java or css way to hide it until the loop is done or you want to display stuff.