PHP undefined offset - php

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().

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

Using a function to query a database

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>

Open different modal-diaglog with foreach()

I'am trying to implement a modal that shows always different information. This depends on the name you click. At this moment he always shows the modal of the latest link.
Here I'm printing out the different information. For each line i want a specific modal
PHP
foreach ($badgesNotifications as $notifications) {
echo "<p>Congratulations! You've earned the <a href='#' data-reveal-id='myModal'>" . $notifications['challenge_badge_title'] ." badge</a></p>";
echo "<div id='myModal' class='reveal-modal' data-reveal>
<h2>" . $notifications['challenge_title'] . "</h2>
<p class='lead'>Your couch. It is mine.</p>
<p>" . $notifications['challenge_description'] . " </p>
<a class='close-reveal-modal'>×</a>
</div>";
}
?>
I tried to replace 'myModal' with $notifications['challenge_badge_title'] in the link and the id of the mail but then he isn't opening the modal.
The title is always different so I thought he would open an other window. The id don't have to be necessary "MyModal" because it's working with other words to.
I also tried to put the data in different arrays because they are overwriting each other. But also that won't fix my problem.
public function BadgeNotifications($user_id)
{
$db = new Db();
$select = "SELECT
c.challenge_id,
c.challenge_title,
c.challenge_target,
c.challenge_description,
c.challenge_badge_img,
c.challenge_badge_title,
p.challenge_id,
p.user_id,
p.challenge_progress
FROM (tblchallenges c INNER JOIN tblchallenges_progress p ON c.challenge_id = p.challenge_id) WHERE p.user_id = " . $user_id . " ";
$result = $db->conn->query($select);
$result_count = mysqli_num_rows($result);
$result_array = array();
for($i = 0; $i < $result_count; $i++)
{
$result_data = mysqli_fetch_assoc($result);
$result_array[$i]["challenge_id"] = $result_data["challenge_id"];
$result_array[$i]["challenge_title"] = $result_data["challenge_title"];
$result_array[$i]["challenge_description"] = $result_data["challenge_description"];
$result_array[$i]["challenge_badge_title"] = $result_data["challenge_badge_title"];
}
return $result_array;
}
It looks like there's an error here with your code:
echo "<div id='myModal' class='reveal-modal' data-reveal>";
You should perhaps give each modal a unique ID. Properly written Javascript applications fall over when ID's are used more than once as the CSS/JS specification says that you may only use an ID once.
My solution below introduces an iterator $i which you can use to make each echoed element unique.
You will notice that the modal ID now has a number at the end of it, (myModal0, myModal1, etc.).
foreach ($badgesNotifications as $i => $notifications)
{
echo "<p>Congratulations! You've earned the <a href='#' data-reveal-id='myModa" . $i . "l'>" . $notifications['challenge_badge_title'] ." badge</a></p>";
echo "<div id='myModal" . $i . "' class='reveal-modal' data-reveal>
<h2>" . $notifications['challenge_title'] . "</h2>
<p class='lead'>Your couch. It is mine.</p>
<p>" . $notifications['challenge_description'] . " </p>
<a class='close-reveal-modal'>×</a>
</div>";
}
?>

PHP/MySQL - Trying to Pass Query Variables From MySQL Fetch Array Through Page URL

I'm running a script that fetches a row from a MySQL table and is supposed to then pass certain variables from that row to the next page to be used in a form that allows user updating.
Here's the excerpt from the script that is trying to pass the variables to the next page:
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
}
If I omit everything after "&game_id=" in the href, it displays fine. However, once I start adding the variables, it cuts off the function and stops displaying the page.
Am I doing something simple wrong with the syntax? I've tried playing around with different ways to write it, but to no avail. Do I need to utilize a http_build_query() to make this work?
Here's the entire script code if you need more info:
<?php
// Connect to the database:
require ('../mysqli_connect.php');
// Make the query for games from the schedule database and determine the game location:
$q = "SELECT tl.game_date, tl.game_time, tl.away_team, tl.home_team, tl.home_score,tl.away_score, tl.arbiter_id, us.football_location, us.football_map
FROM test_league tl
INNER JOIN user_schools us ON (tl.home_team = us.school_name)
ORDER BY tl.game_id";
$r = mysqli_query($db, $q);
// Declare two variables to help determine the background color of each row:
$i = 0;
$bgcolor = array('row1', 'row2');
// Begin function to print each game as a row:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<tr class="' . $bgcolor[$i++ % 2] .'"><td>' . $row['game_date'] . '</td><td>' . $row['game_time'] . '</td><td class="alignleft">' . $row['away_team'] . ' vs<br>' . $row['home_team'] . '</td>';
// Determine if the score has been reported:
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
} else {
echo '<td>' . $row['home_score'] . '<br>' . $row['away_score'] . '</td>';
}
echo '<td>' . $row['football_location'] . '</td><td>' . $row['arbiter_id'] . '</td></tr>';
}
mysqli_free_result ($r);
mysqli_close($db);
?>
Any and all advice is greatly appreciated!
Try this, you've got your speech marks and dots mixed up :)
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
}
Hope this helps!
$url = 'www.example.com?' . http_build_query($row,'','&');

Using PHP to show "Next" an "Previous" in pagination

I am using the following code:
$result = mysql_query("SELECT * FROM table LEFT JOIN table2
ON table.field = table2.field WHERE ( table.field = '$pid' )
AND ( table.field5 LIKE '%$q%' OR table.field3 LIKE '%$q%'
OR table2.field2 LIKE '%$q%' )");
if (empty($what)) {
$countpls = "0";
} else {
$countpls = mysql_num_rows($result);
}
<?php
if ($countpls > 10) {
echo '<a id=pgnvg href="' . $_SERVER['PHP_SELF'] . '?pg=' . ($startrow + 20) . '&q=' . ($what) . '">Next</a>';
} else {
echo "";
}
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo '<a id=pgnvg2 href="' . $_SERVER['PHP_SELF'] . '?pg=' . $prev . '&q=' . ($what) . '">Previous</a>';
} else {
echo "";
}
?>
I want the next to show only if there are more entries to show and previous only if there are more entries to circle back to. It works on the first page bt then on the last page Next shows despite teh fact that there are no more results to show.
I tried adding the 'else' but its still not working.
Any ideas?
if($countpls > 0){
$pg = $_POST['pg']?$_POST['pg']:1;
//if it's not the first page...
if($pg>1){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg-1).'&q='.$what.'">Previous</a>';
}
//if you have more registers to show...
if(($countpls-(($pg-1)*10))>10){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg+1).'&q='.$what.'">Next</a>';
}
}
In order to calculate your offset to use in queries, use this:
$offset = ($_POST['pg']-1)*10;
It would help if you would provide the code that's setting $countpls. That might be the part that's causing the problem. Also, the else's are unnecessary. However, try this:
if($countpls - $startrow > 20)
{
echo '<a id=pgnvg href="'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&q='.($what).'">Next</a>';
}
I think it would do you good if you followed a tutorial to grasp the basic concepts. It even comes with the example that could either 1.) replace your current pagination or 2.) fix it.
http://www.phpfreaks.com/tutorial/basic-pagination

Categories