Replacing characters with smileys from echoed row - php

I can't figure this out and isn't my strong side of codeing ether.
As of right now it'll only print the first person and timestamp, not anything more.
<table cellpadding="0" cellspacing="0" width="100%">
<tr><td></td></tr>
<?php
include '../connection.php';
$sql = "SELECT *
FROM messagebox
INNER JOIN person
ON messagebox.sid = person.sid
ORDER BY messagebox.id DESC
LIMIT 20
";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
if ($switch=='1')
{
echo "<tr bgcolor=\"#FFFFFF\">";
$switch='0';
}
else
{
echo "<tr bgcolor=\"#F9F9F9\">";
$switch='1';
}
$elfstring = utf8_encode($row['shout']);
function smiley($elfstring) {
$elfstring = ereg_replace(":)","<img src=!.png alt=\"!\" >", $elfstring);
$elfstring = ereg_replace(":(","<img src=laugh.gif alt=\":D\" >", $elfstring);
$elfstring = ereg_replace(":p","<img src=tongue.gif alt=\":p\" >", $elfstring);
return $elfstrings;
}
$messages = smiley($elfstring);
echo "";
echo "<td width=\"100\" valign=\"top\"><strong>" . $row['name'] . "</strong></td>";
echo "<td width=\"100\" valign=\"top\">" . "(" . $row['place'] .")</td>";
echo "<td width=\"70\" valign=\"top\">" . "" . date('H:i:s',strtotime ($row['timestamp'])) ."</td>";
echo "<td valign=\"top\">" . smiley($elfstrings) . "</td>";
echo "</tr>";
}
?>
<tr>
<td>
</td>
</tr>
</table>
I know some parts of this code is deprecated, but the server using this is old and isn't up to date.
Thanks in advance for help.

You can't declare a function multiple times. Move the function smiley(){ outside of your while loop.
You should enable error reporting and monitor your error logs.
You should indent each control block so you can easily tell where blocks end/start.
If you don't need a regex/ aren't using one don't use a regex function. The ( and ) are special regex characters and will cause errors. Use str_replace because you are doing static replacements anyway.
You can enclose strings in " or ', this can simplify string construction because you won't need to escape.
So make the ending of your script:
function smiley($elfstring) {
return str_replace(array(':)', ':(', ':p'),
array('<img src="!.png" alt="!" >', '<img src="laugh.gif" alt=":D" >', '<img src="tongue.gif" alt=":p" >'),
$elfstring);
}

Related

PHP passing values from generated textboxes

I'm creating a PHP web application in combination with SQL to order stuff. I'm randomly generating textboxes based on the amount of records I have. I want to pass the individual values to insert to the database. I want each cell to have a textbox in which I can input values and pass them with that cell. So if I want to order 2 of cell one I want to pass that value into a database.
Here's the code:
$i = 0;
if ($AanbodsTabel === false){
die(mysql_error());
}
while ($row = mysqli_fetch_array($AanbodsTabel)){
echo "<tr><td width = 4%>". htmlentities($row['Fustcode']) . "</td>";
echo "<td width = 8%>" . htmlentities($row['cultivar']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalPerFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelen']) . "</td>";
echo "<td width = 4%><input type ='text' id='Bestelbox' value='' name='AantalBestellen".$i."'></td>";
echo "<td width = 6%>" . htmlentities($row['AantalFustBesteld']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelenBesteld']) . "</td>";
135: echo '<td width = 8%><a href="Home.php?aanbodid='. htmlentities($row['aanbodid']) .'&hoeveelheid='. $_GET["AantalBestellen$i"]. '"'
. ' class = "btnBestel">Bestel</a></td></tr>';
$i = $i + 1;
}
The error I'm getting is undefined index. I guess this is because the name isn't unique. But whatever I do I still get the error.
I'm getting:
undefined index: AantalBestellen0 on line 135;
you can use javascript for example
note i will bold the code you need, the rest is context.
note this is from a similar project of mine but you should get the point.
<div id="meldingen_top_div">
<?php
echo "<div class='alert_Top_Div_Left_Outer'>
<input type='submit' value='Openstaande Meldingen' class='btnLoad' name='' onclick='toggleThis(" . '"' . "#meldTableTop" . '"' . "), toggleThis(".'"'.".alert_Top_Div_Left_Inner".'"'.")'/>
<div class='alert_Top_Div_Left_Inner'>
<table class='tableRed' id='meldTableTop'><caption/><thead/><tfoot/><tbody>";
$sqlVII = "SELECT Meldingen.Melding_id, FORMAT(Meldingen.Melding_datum, 'dd-mM-yyyy') AS Melding_datum, Producten.Product_naam, Leveranciers.Leverancier_naam, Meldingen.Melding_notitie
FROM MovieWorld.dbo.Producten,
MovieWorld.dbo.Meldingen,
MovieWorld.dbo.Categorieen,
MovieWorld.dbo.Leveranciers
WHERE Producten.Product_id = Meldingen.Product_id AND Producten.Categorie_id = Categorieen.Categorie_id AND Categorieen.Leverancier_id = Leveranciers.Leverancier_id AND Producten.Product_actief = 1 AND Meldingen.Melding_actief = 1
";
$resV= $db->executeQuery($sqlVII);
$i=1;
if($resV!=FALSE){
while($arrx = sqlsrv_fetch_array($resV)){
Code wich is relevant for you:
echo "<tr>
<td><p class='meldDate'>{$arrx['Melding_datum']}</p></td>
<td>{$arrx['Product_naam']}</td>
<td>{$arrx['Leverancier_naam']}</td>
<td><input id='txt{$i} type='text' name='thisdoesntevenmatter' value='..'/></td>
<td><img src='somerandompath.png' onclick='getTxt(".'"txt{$i}"'.")'/></td>
</tr>"
$i=$i+1;
}
}else{}echo '</tbody></table></div></div>';
?>
</div>
and the Javascript function
function getTxt(id){
var tempId = document.getElementById(id).value;
return tempId;
}
however.. you can also send the value back into a php variable, OR use AJAX to pass it to an PHP class to insert it into the Database.
edit
Your quotes in line 135: seem incorrect. try this:
echo '<td width = 8%><a href="Home.php?aanbodid={htmlentities($row['aanbodid']) }&hoeveelheid={$_GET['AantalBestellen$i']}"'
. ' class = "btnBestel">Bestel</a></td></tr>';
Where you get undefined index? on that $_POST['AantalBestellen'] ?
Use
if (isset($_POST['AantalBestellen'])) { }
to identify that the post value has been set
same do later for the hoeveelheid:
if (isset($_GET['hoeveelheid'])) { }
echo-ing the input field:
echo "<td width = 4%><input type ='text' id='Bestelbox' value='" . $_GET['hoeveelheid'] . "' name='AantalBestellen'></td>";
Also, dont forget to clear the spaces in:
'&hoeveelheid = '. $_POST //near the =

Delete index session in PHP

I have question referring to the session in PHP.
I've coded in PHP for setting the session and I want to delete it , but I got some errors and confusing with using the UNSET(variable $_SESSION). Perhaps anyone could help me to show what should I do with this matter. Thanks in advance
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['index'] = 0
$_SESSION['chart'][0]['type'] = $type;
$_SESSION['chart'][0]['idanimal'] = $iddog;
$_SESSION['chart'][0]['price'] = $price;
printdata(); // <== this is the function to print out the data
All I want to do is just delete based on the index in this session
Here's the function :
function printdata()
{
$totalharga = 0;
if(is_array($_SESSION['chart']))
{
echo "<h3>"."Berikut adalah keranjang belanja anda" . "</h3>". "<br>";
$max = count($_SESSION['chart']);
$th1 = "<th>" . "No" . "</th>";
$th2 = "<th>" . "Animal Type" . "</th>";
$th3 = "<th>" . "ID Binatang" . "</th>";
$th4 = "<th>" . "Harga" . "</th>";
$th5 = "<th>" . "Hapus Data" . "</th>";
echo "<table border=1>";
echo "<tr>";
echo $th1 ;
echo $th2;
echo $th3;
echo $th4;
echo $th5;
echo "</tr>";
for ($indexo = 0; $indexo < $max; $indexo++)
{
echo "<tr>";
echo "<td>" . $indexo."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['type']."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['idanimal']."</td>";
echo "<td>" . "Rp. " . $_SESSION['chart'][$indexo]['harga']. ",-" ."</td>";
echo "<td>" . "<a href='deletesession.php?session=$indexo'>" ."Proses ". "</a>"."</td>";
$totalharga += $_SESSION['chart'][$indexo]['harga'];
echo "</tr>";
}
echo "</table>" . "<br/>";
echo "<blockquote>" . "Total Pembelian Item Yang Anda Pesan =". "<h2>". "Rp." . $totalharga . ",-" ."</h2>" . "</blockquote>";
}else
{
echo "Chart is still Empty";
}
}
I've already tried this :
Suppose that there is a chart already filled by the contents then I tried to delete within this code, I've received error with the unset variable
unset($_SESSION['chart'][1])
Thank you
I spot several things that could be improved in your code:
Don't echo in your functions, return instead (then echo what the function returns). This gives you more flexibility regarding what you do with your result.
PHP has a built-in loop for iterating arrays, the foreach loop. You should be using that instead of for.
So here's what I have:
function print_session_data($session) {
if (!is_array($session)) {
return "Array is empty";
}
$table_data = "";
$total_harga = 0;
foreach ($session as $index => $data) {
$table_data .= <<<TABLE_DATA
<tr>
<td>$index</td>
<td>{$data["type"]}</td>
<td>{$data["idanimal"]}</td>
<td>Rp. {$data["harga"]}</td>
<td>Proses</td>
</tr>
TABLE_DATA;
$total_harga += $data["harga"];
}
$result = <<<RESULT
<h3>Berikut abalah keranjang belanja anda</h3>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>Animal Type</th>
<th>ID Binatang</th>
<th>Harga</th>
<th>Hapus Data</th>
</tr>
</thead>
<tbody>
$table_data
</tbody>
</table>
<blockquote>Total Pembelian Item Yang Anda Pesan = <strong>Rp. $total_harga</strong></blockquote>
RESULT;
return $result;
}
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['type'] = "Type";
$_SESSION['chart'][0]['idanimal'] = 6;
$_SESSION['chart'][0]['price'] = '$25';
$_SESSION['chart'][0]['harga'] = 25;
echo print_session_data($_SESSION["chart"]); // <== this is the function to print out the data
Suppose that there is a chart already filled by the contents then I
tried to delete within this code, I've received error with the unset
variable unset($_SESSION['chart'][1])
From what I can see from your code the best way to unset the data correctly is as follow:
DEMO.
You have to check if the $_SESSION['chart'][0] was set before using the session variable index again. If it $_SESSION['chart'] array still contains other indexes then you can call printdata(); else indicate that the session was empty.

PHP Facebook FQL Multquery and dealing with foreach and variables

Alright, so I am trying to figure this out. Basically I have everything working well except for adding the cover photos to each of the DIVS. Basically I have 2 queries using FQL, and here is my code.
$query =
'{"query1":"SELECT aid, cover_pid, name, description FROM album WHERE owner=$fbowner",
"query2":"SELECT src FROM photo WHERE pid IN (SELECT cover_pid FROM #query1)"}';
$fqlResult = $facebook->api(array(
'method' => 'fql.multiquery',
'queries' => $query));
$fql = $fqlResult[0]['fql_result_set'];
$covers = $fqlResult[1]['fql_result_set'];
$the_count = count($fql);
$i = 0;
foreach($fql as $value) {
$album_cover = $value['src'];
echo "<div class='fb_block'>";
echo "<a href='" . $url . "?action=list_pics&aid=" . $value['aid'] . "&album_name=" . $value['name'] . "'>";
echo "<img src='{$covers[$i]['src']}' border='1'>";
echo "</a>";
echo "<h3>".$value['name']."</h3>";
echo "<p>".$value['description']."</p>";
echo "</div>";
$i++;
}
Now that works fine, but what if I put this in the mix, the cover photos are all off unless I make $i = 1.
$i = 0;
foreach($fql as $value) {
if($value['name'] != 'Wall Photos'){
$album_cover = $value['src'];
echo "<div class='fb_block'>";
echo "<a href='" . $url . "?action=list_pics&aid=" . $value['aid'] . "&album_name=" . $value['name'] . "'>";
echo "<img src='{$covers[$i]['src']}' border='1'>";
echo "</a>";
echo "<h3>".$value['name']."</h3>";
echo "<p>".$value['description']."</p>";
echo "</div>";
$i++;
}
}
and if I stick another foreach in the mix, it grabs all the cover photos and sticks them into each div. So what is the easiest solution to just go in order and grab the cover photo associated with the album node?
Thanks in advance!
I tried this, too. You can't rely on the indexes being consistent between these two queries.
To make it work, first modify query2 to also return pid, then replace this line in your code:
echo "<img src='{$covers[$i]['src']}' border='1'>";
with this:
foreach($covers as $cover) {
if ($value['cover_pid'] === $cover['pid']) {
echo "<img src='{$cover['src']}' border='1'>";
break;
}
}

How can I put HTML tags in a PHP variable?

I am trying to make a variable which contains some HTML tags, this isn't working like I want it to. I was hoping someone could tell what I am doing wrong here.
My Code:
$foto = "put picture here";
$naam = 'Sieraad1';
$prijs = '20,00';
$artikel = '<img src="'$foto'"><h4>'$naam'</h4><h6>€'$prijs'</h6>';
echo '<table><tr><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td></tr>';
echo '<table><tr><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td></tr>';
echo '</table>';
$artikel = '<img src="'$foto'"><h4>'$naam'</h4><h8>€'$prijs'</h8>';
You are missing . here between the variables for concatenation.
Using htmlspecialchars on html code will convert < to <, > to > and " to ". So it will obviously break your code. Run the htmlspecialchars on the inner contents instead:
$artikel = '<img src="' . htmlspecialchars($foto) . '"><h4>' . htmlspecialchars($naam) . '</h4><h8>€' . htmlspecialchars($prijs) . '</h8>';
echo '<table><tr><td>'.$artikel.'</td>...';
var concatenation is missing for variable $artikel. replace user code line with below:
$artikel = '<img src="'.$foto.'"><h4>'.$naam.'</h4><h8>€'.$prijs.'</h8>';
easy to use
<?php
echo <<< END
<table class="head"><tr>
<td class='head'>$name</td>
<td>$fname</td>
</tr></table>
END;
?>
or
<?php
echo "<table class='head'><tr>
<td class='head2'>$name</td>
<td class='head3'>$fname</td>
</tr></table>";
?>
try
$artikel = "<img src=\"'$foto'\"><h4>'$naam'</h4><h8>€'$prijs'</h8>";
or
$artikel = '<img src="' . $foto . '"><h4>' . $naam . '</h4><h8>€' . $prijs .'</h8>';
then just echo the $artikel - you don't need the htmlspecialchars

Couldn't fetch mysqli...Call to a member function fetch_assoc() on a non-object

I'm totally baffled. My entire page code is below.
Originally, I had the include header.php, sidebar, topMenuBar, & mainContentShell at the top of the page, ran the first query after it, and then the second query, etc for the rest of the page. Everything worked. My first query was different though... I checked that the $_GET['stone'] number was greater than zero and less than the select max(StoneID), but I could still get errors if someone manually put in the StoneID for a stone that was deleted from inventory. I revised my $_GET validation plan, and moved it above the included files so the header() redirect would work properly. Now, my second query won't work, even though it is completely unchanged.
Var_dump($querySN) yields string(53) "select StoneName from stonetypes where StoneID = '1' " and var_dump($resultSN) yields NULL.
It states: error occurred at line 35 --- $resultSN = $db->query($querySN);
States several times: Couldn't fetch mysqli
States a number of times: Property access is not allowed yet
And states in conclusion: Call to a member function fetch_assoc() on a non-object on line 36---$rowSN = $resultSN->fetch_assoc();
Does anyone know what's going on here and how I can fix it? Page code follows. Thanks!!!
<?php
require('./inc/config.inc.php');
$stone = (INT)$_GET['stone'];
require(MYSQL1);
$queryCk = "select StoneID from stonetypes";
$resultCk = $db->query($queryCk);
$var = array();
while ($rowCk = $resultCk->fetch_assoc()){
$var[] = $rowCk['StoneID'];
}
if(!in_array($stone, $var)) {
header('Location: beadgallery.php?type=stones');
exit;
} else {
include('inc/header.inc.php');
include('inc/sidebar.inc.php');
include('inc/topMenuBar.inc.php');
include('inc/mainContentShell.inc.php');
?>
<div id="mainContent">
<div class="center">
<?php
$querySN = "select StoneName from stonetypes where StoneID = '$stone' ";
$resultSN = $db->query($querySN);
$rowSN = $resultSN->fetch_assoc();
echo '<table id="cartDisplayTable">';
echo '<tr>';
echo '<td colspan="2">';
echo '<table id="titleTable">';
echo '<tr>';
echo '<td id="stoneTitle">';
if (isset($rowSN['StoneName'])){
echo '<h2>'.ucwords($rowSN['StoneName']).'</h2>';}
echo '</td>';
echo '</tr>';
$query = "select * from organized_inventory2 where StoneID = '$stone' ";
$result = $db->query($query);
$num_beadItems = $result->num_rows;
$justused='abc';
for ($i=0; $i < $num_beadItems; $i++) {
$row = $result->fetch_assoc();
if (!isset($row['itmphoto'])) {
echo '</table>';
echo '</td>';
echo '</tr>';
echo '<tr><td colspan="2"><hr id="cartDivider"></td></tr>';
echo '<tr>';
echo '<td id="cartImgCell">';
echo '<img src="img/nophoto.gif">';
echo '</td>';
echo '<td id="cartInfoCell">';
echo '<table id="innerTable">';
include ('inc/stoneCartInfo.inc.php');
} elseif ($row['itmphoto'] == $justused) {
echo '<tr><td colspan="2"><hr id="itemDivider"></td></tr>';
include ('inc/stoneCartInfo.inc.php');
} else {
echo '</table>';
echo '</td>';
echo '</tr>'
;
echo '<tr><td colspan="2"><hr id="cartDivider"></td></tr>'
;
echo '<tr>';
echo '<td id="cartImgCell">';
echo '<img src="img/invent/'.$row['itmphoto'].'">';
$justused = $row['itmphoto'];
echo '</td>';
echo '<td id="cartInfoCell">';
echo '<table id="innerTable">';
include ('inc/stoneCartInfo.inc.php'); }
}
echo '</table>'
;
echo '</td>';
echo '</tr>'
;
echo '</table>'
;
}
$result->free();
unset($result);
$db->close();
?>
</div> <!-- div class="center" -->
</div> <!-- div id="mainContent" -->
Integers don't nee quotes around the value as in StoneID = '1', this shouldn't be a problem because MySQL should typecast.
You have not checked what "$result" contains, if it's boolean then the query failed and you need to see the output of mysqli_error.

Categories