Using a function to query a database - php

I have a page and I would really like some help / advice to create a better way / function to call in information from another table.
At the moment, my code looks like:
[I do know this is deprecated SQL and would really like to do some nice SQLi for this.]
<?
$menuid = "100";
$imageid = "50";
// ** Talk to 'imagedirectory' table
mysql_select_db($database_db, $BASEdb);
$query_displayimage = "SELECT * FROM imagedirectory WHERE menuid = ".$menuid." AND imageid = ".$imageid."";
$displayimage = mysql_query($query_displayimage, $BASEdb) or die(mysql_error());
$row_displayimage= mysql_fetch_assoc($displayimage);
?>
<img src="/images/assets/<?php echo $menuid; ?>-<?php echo $imageid; ?>-<?php echo $row_displayimage['urlslug']; ?>.jpg" alt="<?php echo $row_displayimage['alttext']; ?>" />
I figure There really has to be a better way because if there is 10 images on a page, this is pretty intense way of doing it.

Since you seem to know that mysql_* is deprecated, I am assuming you have read up on, and are using mysqli_* instead.
You needn't query the database every time. mysqli_query() returns a mysqli_result, which you can iterate over, and read using functions like mysqli_fetch_assoc(). Here is one way of doing it:
<?php
// store your query in a variable.
$query_displayimage = "SELECT * FROM imagedirectory";
// query the database.
$displayimage = mysqli_query($query_displayimage, $BASEdb);
// check for errors.
$dbErrors = mysqli_error($BASEdb);
if (count($dbErrors))
{
print_r($dbErrors);
die();
}
// iterate over the returned resource.
while ($row_displayimage = mysql_fetch_assoc($displayimage))
{
echo '<img src="/images/assets/' . $menuid . '-' . $imageid . '-' . $row_displayimage['urlslug'] . '.jpg" alt="' . $row_displayimage['alttext'] . '" />';
}
?>
Hope that helped.
EDIT:
You can use this code in a function, too. For example:
<?php
function printImage($menuid, $imageid)
{
$query_displayimage = "SELECT * FROM imagedirectory";
$displayimage = mysqli_query($query_displayimage, $BASEdb);
$dbErrors = mysqli_error($BASEdb);
if (count($dbErrors))
{
print_r($dbErrors);
die();
}
if ($row_displayimage = mysql_fetch_assoc($displayimage))
{
echo '<img src="/images/assets/' . $menuid . '-' . $imageid . '-' . $row_displayimage['urlslug'] . '.jpg" alt="' . $row_displayimage['alttext'] . '" />';
}
else // if there is a problem getting the image
{
echo 'Error getting image.';
}
}
?>
and elsewhere in your HTML, you would do something like:
<div>
And here is an image!
<?php printImage(20, 50); ?>
</div>

Related

php echo iframe or image

Hey everyone I am having an issue with echoing an image or an iframe, the idea is there is an image link or an iframe in the same row in the database & i want to only echo what the string content is, if it echos the iframe there is a blank space of an image & underneath is the youtube video, if it echos the image the iframe does not show, they both currently echo the same row id labled url, I only want one to echo based on the string content instead of both echo's.
Here is the code I use to fetch the stuff, its only the echo area you want to pay attention to, I am not sure what kind of, if or else statement i could put in here.
< ?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 4;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM bookmarks WHERE 1 ORDER BY id DESC LIMIT $limit OFFSET
$offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
echo '<img src=' . $row['url'] . '></br>'; /*here */
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
} }
?>
This script is a get results php
The best solution would be to save the data in different columns in the database. But if you want to keep the current structure would be able to check if the string contains HTML, then it is an iframe. Otherwise it is a link to the image.
<?php
if($row['url'] == strip_tags($row['url'])) {
//No HTML in string = link
echo '<img src="' . $row['url'] . '" alt="" />';
} else {
//Contains HTML = iframe
echo $row['url'];
}
?>
This assumes that you in your database have saved the values as either http://www.exempel.com or <iframe src =" http: // www ... ">. If the iframe-value also consists only of a URL, you must use another solution.
If you know whether the url is an image or video when you save them in the database then you could add another field for the media type. You could then use this in an if statement in your code, for example:
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
if ($row['mediaType'] === 'image') {
echo '<img src=' . $row['url'] . '></br>'; /*here */
} if ($row['mediaType'] === 'video') {
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
}
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
}
}

Showing specific information of current user logged in, in PHP

I'm using this 2 plugins
http://www.wpexplorer.com/wordpress-user-contact-fields/
and
WooCommerce
The 1st parameter, in this case the number "1" refers to the id of the user, how con I change it to be dynamic? So, depending on the user I get its own specific information
<h2>Personal</h2>
<?php
echo '<ul>';
echo '<li>Direccion: ' .get_user_meta(1,'address',true) . '</li>';
echo '<li>CompaƱia: ' .get_user_meta(1,'company',true) . '</li>';
echo '<li>Birth dAte: ' .get_user_meta(1,'birth',true) . '</li>';
echo '<li>Gender: ' .get_user_meta(1,'gender',true) . '</li>';
echo '<li>phone: ' .get_user_meta(1,'phone',true) . '</li>';
echo '</ul>';
?>
thanks
Don't try to make a function do something it wasn't intended to do. Write your own. Especially for something this simple.
function getUserStuff($id, $item){
$item = mysql_real_escape_string($item);
$id = mysql_real_escape_string($id);
$q = mysql_query("SELECT `".$item."` FROM `users` WHERE `id` = '".$id."'");
$z = mysql_fetch_assoc($q);
return (mysql_num_rows($q) > 0) ? $z[$item] : false;
}
This is just an example. I used a deprecated function for simplicity but you should use a different API.

Why is this 1 image showing an infinite number of times?

$pgroup = $Sys->db->query("SELECT dj_photo_group.photo_group, dj_photo.name FROM dj_photo_group, dj_photo WHERE dj_photo_group.photo_group = dj_photo.img_group ORDER BY dj_photo.img_group DESC");
while($photo = $pgroup->fetch_object()) {
echo '<div class="photo_head">' . ucfirst($photo->photo_group) . '</div>';
echo '<div class="photo_sub">';
while($photo->name) {
echo '<img src="photogallery/' . $photo->photo_group . '/' . $photo->name . '" />';
}
echo '</div>';
}
This is showing the same 1 image over and over again. I have 3 groups: Wedding, 5points and Misc that have 2 images each. It only shows Weddings with 1 image infinite number of times.
What am I doing wrong and how can I fix it?
$photo->name is always true. So if you use it in a while loop, you're essentially saying:
while(true){
// do this
}
Remember, while loops will keep going as long as the condition specified is true.
You should really be using an if statement instead.
if($photo->name){
// do this
}
while($photo->name) will repeat until $photo->name is false. Because in the loop there is nothing that will change it, it will always be true, and so the loop continues forever.
Like Nishant said, you want to replace it with an if statement.
while($photo->name) is entering into infinite loop as the condition is always true. You should put an end condition to this while loop or otherwise you can go for if condition also
if($photo->name)
Try this.. this solution will provide you your desired layout....
$pgroup1 = $Sys->db->query("SELECT dj_photo_group FROM photo_group GROUP BY dj_photo_group");
while ($photo1 = $pgroup1->fetch_object())
{
echo '<div class="photo_head">' . ucfirst($photo1->dj_photo_group) . '</div>';
echo '<div class="photo_sub">';
$pgroup2 = $Sys->db->query("SELECT name FROM dj_photo WHERE img_group = '$photo1->dj_photo_group'");
while ($photo2 = $pgroup2->fetch_object())
{
echo '<img src="photogallery/' . $photo1->dj_photo_group . '/' . $photo2->name . '" />';
}
echo '</div>';
}

PHP undefined offset

I am making a photo gallery and with every photo I can see how many comments there are on that photo. The code that I have is working like it should except that if there are 0 comments it will give the 'Undefined Offset error: 2'
'Undefined Offset error: 3'
'Undefined Offset error: 4'
'Undefined Offset error: 5'
etc.
This is the code to check how many comments there are:
(reacties = comments)
// check how many comments every photo has.
$reacties;
$query = "select foto from fotosreacties where boek = '" . $_GET['boek'] . "'";
if($result = mysql_query($query)){
while ($r = mysql_fetch_array($result)){
while ($foto = current($fotoArray)) {
if ($foto==$r["foto"]){
$key = key($fotoArray);
} // end if
next($fotoArray);
} // end while
if(!isset($reacties[$key])){
$reacties[$key] = 1;
} // end if
else {
$reacties[$key]++;
} // end else
reset($fotoArray);
} // end while
} // end if
And this is the code to show the picture and the number of comments:
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
If anyone knows what I have done wrong and/or knows how to solve this it would be great!
You can embed the counter in your query:
select foto, count(*) AS counter_comments from fotosreacties where boek = '" . $_GET['boek'] . "'. In the result, you can use $r['counter_comments'] and check whether its 0 or more.
About your code:
Stop using MySQL-functions in new applications since they will be deprecated soon. Use MySQLi or PDO instead!
Never trust user input like $_GET, you at least sanitize it by (for example) mysql_real_escape_string().

How to use Caching Feature of PHP last.fm API

I'm using PHP last.fm API to fetch artist image
I'd like to know how to cache the calls so that I don't need to make same call again and again. The API has facility to cache : DiskCache, SqliteCache but there is no documentation, could anyone please shed some light on it?
Below is my code :
<?php
require __DIR__ . "/src/lastfm.api.php";
// set api key
CallerFactory::getDefaultCaller()->setApiKey(LAST_FM_API_KEY);
// search for the Coldplay band
$artistName = "Coldplay";
$limit = 1;
$results = Artist::search($artistName, $limit);
echo "<ul>";
while ($artist = $results->current()) {
echo "<li><div>";
echo "Artist URL: " . $artist->getUrl() . "<br>";
echo '<img src="' . $artist->getImage(4) . '">';
echo "</div></li>";
$artist = $results->next();
}
echo "</ul>";
?>

Categories