Show image title in a javascript pop up? - php

I'm having trouble with a javascript pop up. I want the pop up to show the image reason/Title.
Anyone know what to do?
The code:
<?
$badgesql = mysql_query("select * from usr_badge where user = '$_SESSION[usr_name]'");
$user = mysql_query("select * from usr_users where username = '$_SESSION[usr_name]'");
$usr = mysql_fetch_array($user);
$vipsql = mysql_query("select * from usr_vip where userid = '$usr[id]'");
$vipcheck = mysql_num_rows($vipsql);
$badgecheck = mysql_num_rows($badgesql);
$checkit = $badgecheck + $vipcheck;
if($checkit==0)
echo("You have 0 Badges");
if($badgecheck!=0)
{
while($badge = mysql_fetch_array($badgesql))
{
echo('<img src="/css/badges/'.$badge[badge].'" onclick="alert('.$badge[reason].');" />'); }
}
//Display VIP Badges
if($vipcheck!=0)
{
$vipbadge = mysql_fetch_array($vipsql);
$vip1 = mysql_query("select * from usr_vipdb where id = '$vipbadge[vipid]'");
$vip2 = mysql_fetch_array($vip1);
echo('<img src="'.$vip2[url].'" alt="This user is a VIP!" />');
}
?>
Thanks in advance!

The problem is you need some quotes within your alert().
echo('<img src="/css/badges/'.$badge['badge'].'" onclick=\'alert("'.htmlentities($badge['reason']).'");\' />');
Also, $badge[reason] is bad practice (unless reason is a constant which I don't think is). Use single quotes like in the example above.
Finally, use htmlentities() when you're printing content to HTML.

The inline JavaScript isn't exactly a proper one. When you echo the string the onclick attribute will contain the value that looks something like:
alert(image reason);
You need to enclose the reason of the image with quotes for it to work properly. Thus, your code should look like this instead:
echo '<img src="/css/badges/'.$badge[badge].'" onclick="alert(\''.$badge[reason].'\');" />'

Related

search form php/sql multiple inputs

i've a problem with a search form. It works only if I use all the 4 fields, but if a leave a field empty the while loop echoes out all the table's records.
Can someone please help me?
This is my php code for the search function
<?php
if (isset($_POST['cerca'])){
$cerca_tt = $_POST['tt_carrier'];
$cerca_risorsa = $_POST['risorsa_cerca'];
$cerca_team = $_POST['team_cerca'];
$cerca_linea = $_POST['linea_cerca'];
$sql_cerca = "SELECT * FROM normal WHERE
tt LIKE '%".$cerca_tt."%'
OR risorsa LIKE '%".$cerca_risorsa."%'
OR team LIKE '%".$cerca_team."%'
OR linea LIKE '%".$cerca_linea."%'";
if($sql_cerca) {
$trovati = mysql_query($sql_cerca); ?>
if the POST is blank then the variable is blank thus everything will match like '%%'
for example if $cerca_tt is blank. your query would be
"SELECT * FROM normal WHERE tt like '%%'"
that matches everything.
create the query based on the POST response.
$sel = "SELECT * from normal";
//You will need to deal with the WHERE part of the query.
if (!empty($cerca_tt)){
$sel .= " OR tt like '%".$cerca_tt."'";
}
etc....///
If you only provide one search parameter and the rest are empty strings, which you wrap with %, you are effectively searching everything. You need to build up your query. For example (simple):
$sqlParts = [];
if(isset($_POST['tt_carrier'])) {
$sqlParts[] = "tt LIKE '%".$cerca_tt."%'";
}
if(isset($_POST['risorsa_cerca'])) {
$sqlParts[] = "risorsa LIKE '%".$cerca_risorsa."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "team LIKE '%".$cerca_team."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "linea LIKE '%".$linea_cerca."%'";
}
if(!empty($sqlParts)) {
$sql = "SELECT * FROM normal WHERE " . implode(' OR ', $sqlParts);
}

Posting Data To Mysql with IDs

I have a form with some input texts. It's counted with the name + an id. Like:
megnevezes_1
megnevezes_2
My form has also a counted id tag, called tid_1 and go on.
When I post my form i made a hidden input called darab, which counts how many id's I have.
Then I do the mysql query:
for($k=1; $k=$darab; $k++){
$command = <<<HTML
UPDATE
$dbtablename_template_tetelek
SET
vamtarifa_szj = '$vamtarifa_szj_$k',
megnevezes = '$megnevezes_$k',
me_egyseg = '$me_egyseg_$k',
mennyiseg = '$mennyiseg_$k',
afa = '$afa_$k',
egyseg_ar = 'str_replace(".","",$egyseg_ar_$k)'
WHERE template_id = '$tid_$k'
HTML;
mysql_query($command,$kapcsolat) or die(mysql_error(). $command);
}
But theres something wrong with it. How to attach to my strings the $k string with _? And how to make the str replace in the query?
Try this..
for($k=1; $k=$darab; $k++){
$blah = $egyseg_ar . '_' . $k;
$replace = str_replace(".", "", $blah);
$command = <<<HTML
UPDATE
$dbtablename_template_tetelek
SET
vamtarifa_szj = '$vamtarifa_szj_$k',
megnevezes = '$megnevezes_$k',
me_egyseg = '$me_egyseg_$k',
mennyiseg = '$mennyiseg_$k',
afa = '$afa_$k',
egyseg_ar = $replace
WHERE template_id = '$tid_$k'
HTML;
mysql_query($command,$kapcsolat) or die(mysql_error(). $command);
}
You should let PHP know precisely what it needs to parse. To help it you can use curly brackets like in '{$var1}_{$var2}'
So e.g. mennyiseg = '$mennyiseg_$k' might need to be mennyiseg = '{$mennyiseg}_{$k}' if you already have a variable named $mennyiseg in your code above the loop.

getting number from php file with jquery ajax

I'm new to AJAX and jQuery. I'm trying to pass a number from unrate.php to be used as checkVal (as shown below). The file does a bunch of stuff but it only echos the number. When I add a alert(checkVal) it shows a invalid character and than the number I want. (I just want the number)...
ajax handler:
$.get("unrate.php?numb="+ID, function(checkVal){
if (checkVal == 1) {
number.innerHTML = addNumb + 1;
} else {
number.innerHTML = addNumb - 1;
}
});
unrate.php:
<?php
$uNum = $_SESSION['userNum'];
$ider = $_GET['numb'];
$sql = mysql_query("SELECT * FROM ratecheck WHERE ID =".$ider);
$checkRay = mysql_fetch_array($sql);
$checkVal = $checkRay[$uNum];
$sqlZ = mysql_query("UPDATE ratecheck SET `".$uNum."`=0 WHERE ID=".$ider)
or die(mysql_error());
$sqlB = mysql_query("SELECT * FROM sources WHERE ID =".$ider);
$sourceRay = mysql_fetch_array($sqlB);
$newRC = $sourceRay['ratecount'] - 1;
mysql_query("UPDATE sources SET ratecount =".$newRC." WHERE ID =".$ider)
or die(mysql_error());
if ($checkVal > 1)
{
$newpts = $sourceRay['points'] - 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] - 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
else
{
$newpts = $sourceRay['points'] + 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] + 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
echo $checkVal;
mysql_close();
?>
Extra characters at the beginning or end of your output are something you occasionally run into with php. I greatly endorse the comment that suggests looking at the raw output from the server. You might also want to think about these possibilities:
Invisible characters at the beginning or end of your script file. Use a text editor that will show you hidden characters (even a hex editor) and see if there are any. Also, you don't have to end your php script with ?> if you're not doing anything else past it. You can just leave it open, as that will prevent characters showing up at the end.
Check the character encoding that your script has. This might not be the solution, but some time ago I had a similar situation that went away when I changed the encoding to UTF8 without Byte-Order Mark. Try doing the same thing and see if that fixes it

Badge reason error

I'm trying to show badges on our system, badges are rewards/achievement to users. They show on their profile, the thing that works is the image/badge shows, but the badge reason doesn't.
I tried to do it like this
<?
$badgesql = mysql_query("select * from usr_badge where user = '$user'");
$user2 = mysql_query("select * from usr_users where username = '$user'");
$usr2 = mysql_fetch_array($user2);
$vipsql = mysql_query("select * from usr_vip where userid = '$usr2[id]'");
$vipcheck = mysql_num_rows($vipsql);
$badgecheck = mysql_num_rows($badgesql);
$checkit = $badgecheck + $vipcheck;
if($checkit==0)
echo("This user does not have any badges");
else
if($badgecheck!=0)
{
while($badge = mysql_fetch_array($badgesql))
{
echo('<a onclick="TINY.box.show({html:'Reason: '.$badge[reason].',animate:false,close:false,mask:false,boxid:'success',autohide:2,top:-14,left:-17})"><img src="'.$badge[badge].'" </a>');
}
}
//Display VIP Badges
if($vipcheck!=0)
{
$vipbadge = mysql_fetch_array($vipsql);
$vip1 = mysql_query("select * from usr_vipdb where id = '$vipbadge[vipid]'");
$vip2 = mysql_fetch_array($vip1);
echo('<img src="'.$vip2[url].'" alt="This user is a VIP!" />');
}
?>
but that code above doesn't work. It gives me an error when I try to view the page "Parse error: syntax error, unexpected T_STRING in /home/**/public_html/memb.php on line 167"
Can someone please tell me what I'm doing wrong or point me in the right direction?
Thanks in advance
That long line starting with echo is probably at fault -- the syntax highlighting here is broken with it, showing that you've probably mis-matched the quotes or something similar. (Break it apart. Make each small segment on its own line. You won't miss the mistake then.)
Here's your current code broken as I believe the interpreter will parse it:
echo('<a onclick="TINY.box.show({html:'
Reason: '.$badge[reason].'
,animate:false,close:false,mask:false,boxid:
'success'
,autohide:2,top:-14,left:-17})
"><img src="
'.$badge[badge].'
" </a>');
Note the line starting with the bare word Reason:. Since that's not the error you got, perhaps I guessed incorrectly, but there's no doubt that your current code is too messy.
I hope you are sanitizing your inputs ($user, $usr2[id]) and stored data ($badge[reason]) in code that is not shown here to protect against cross-site scripting vulnerabilities and SQL injection vulnerabilities.
Try this (fixed open/close quotes... i think)
<?
$badgesql = mysql_query("select * from usr_badge where user = '$user'");
$user2 = mysql_query("select * from usr_users where username = '$user'");
$usr2 = mysql_fetch_array($user2);
$vipsql = mysql_query("select * from usr_vip where userid = '$usr2[id]'");
$vipcheck = mysql_num_rows($vipsql);
$badgecheck = mysql_num_rows($badgesql);
$checkit = $badgecheck + $vipcheck;
if($checkit==0) {
echo("This user does not have any badges");
} else {
if($badgecheck!=0)
{
while($badge = mysql_fetch_array($badgesql))
{
echo('<a onclick="TINY.box.show({html: "Reason: '.$badge[reason].'",animate:false,close:false,mask:false,boxid:"success",autohide:2,top:-14,left:-17})"><img src="'.$badge[badge].'" /></a>');
}
}
//Display VIP Badges
if($vipcheck!=0)
{
$vipbadge = mysql_fetch_array($vipsql);
$vip1 = mysql_query("select * from usr_vipdb where id = '$vipbadge[vipid]'");
$vip2 = mysql_fetch_array($vip1);
echo('<img src="'.$vip2[url].'" alt="This user is a VIP!" />');
}
}
?>

AJAX -> PHP not updating MySQL database consistently

So this is my early attempt at a Facemash style site in which the user will select one of two images, scoring a hit with the chosen image (the winner) and a miss with the unselected image (the loser) - both of which are recorded in a MySQL database.
The selected image is determined using javascript and uses jquery AJAX to notify a PHP script (backend.php) which updates the database.
This works absolutely correctly for updating the "hits" field. However, the "misses" are not consistently recorded. By this I mean that when the user clicks one image, the fact the other image has not been clicked is only sometimes shown in the database. As far as I can tell there is no pattern as to when the "miss" is and is not recorded, making it difficult to pinpoint where the problem lies.
I've checked the code over and over again and cannot understand why this is happening or what would be responsible for it, so I thought it would be best to post everything. I appreciate it's a lot to ask, but any explaination as to why I'm having this problem would be hugely appreciated, thanks.
<html>
<head>
<title>Facemash</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script>
</head>
<body>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
// Function to return path of photo
function photoPath ($person){
$query = mysql_query("SELECT photo FROM people WHERE id=$person");
$result = mysql_fetch_row($query);
$result = $result[0];
echo $result;
}
?>
<!--Image for personA-->
<div id=photoA identity="<?php echo $personA ?>"><img src="<?php photoPath($personA);?>"/></div>
<!--Image for personB-->
<div id=photoB identity="<?php echo $personB ?>"><img src="<?php photoPath($personB);?>"/></div>
<script type="text/javascript">
$('#photoA').click(function() {
var hit = $('#photoA[identity]').attr('identity');
var miss = $('#photoB[identity]').attr('identity');
$.post ("backend.php", {winner: hit} );
$.post ("backend.php", {loser: miss} );
location.reload(true);
});
$('#photoB').click(function() {
var hit = $('#photoB[identity]').attr('identity');
var miss = $('#photoA[identity]').attr('identity');
$.post ("backend.php", {winner: hit} );
$.post ("backend.php", {loser: miss} );
location.reload(true);
});
</script>
</body>
</html>
backend.php:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Recieve id of winner from index.php
$winner = $_POST['winner'];
// Recieve id of loser from index.php
$loser = $_POST['loser'];
// Lookup hits for winner and update by adding 1
function updateHits ($winner) {
$query = mysql_query("SELECT hits FROM people WHERE id=$winner");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET hits = $result WHERE id=$winner");
}
//Lookup misses for loser and update by adding 1
function updateMisses ($loser) {
$query = mysql_query("SELECT misses FROM people WHERE id=$loser");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET misses = $result WHERE id=$loser");
}
updateHits($winner);
updateMisses($loser);
?>
Thanks again.
Couple things.
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
This doesn't look like it will always guarantee they aren't the same person. The result of the second rand() could again return the same value as $personA
Instead of doing two queries to first select the misses and then increment it, why not make it one query?:
mysql_query("UPDATE people SET misses = misses + 1 WHERE id=$loser");
Lastly, in backend.php, instead of updating winners and losers even if you have only received one of the params, do an if else:
if($winner) {
updateHits($winner);
} else if ($loser) {
updateMisses($loser);
}
I think this will solve your problems.
As a matter of optimization, you should also combine your two POSTs into one.
Try changing your two functions to this and seeing if it will work. (If it doesn't I will just delete my answer.)
// Lookup hits for winner and update by adding 1
function updateHits ($winner) {
mysql_query("UPDATE `people` SET `hits` = hits + 1 WHERE `id`= '$winner'");
}
//Lookup misses for loser and update by adding 1
function updateMisses ($loser) {
mysql_query("UPDATE `people` SET `misses` = misses + 1 WHERE `id` = '$loser'");
}
This probably doesn't cause the problem, but you should only do one $.post and don't duplicate the same functionality in both click handlers.
JS:
$('#photoA, #photoB').click(function() {
var hit = $('#photoA[identity]').attr('identity'),
miss = $('#photoB[identity]').attr('identity');
$.post("backend.php", { winner: hit, loser: miss } );
location.reload(true);
});

Categories