so here is my code and I will tell you the problem after that:
<script language='javascript' type='text/javascript'>
setInterval( function() {
$('#responsechat<?php echo $otherchatuser ?>').load('echogetconversation.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>&numberofmessages=<?php echo $numberofmessages; ?>');
<?php
$subtractlogintime8 = time() - 600;
$data8 = mysql_query("SELECT * FROM loggedin WHERE username='$otherchatuser' and time > '$subtractlogintime'");
$numrows8 = mysql_num_rows($data8);
?>
if (<?php echo $numrows8; ?> == 1 )
{
document.getElementById("checkloggedin<?php echo $otherchatuser; ?>").innerHTML = '<img src="loggedin.png">';
document.getElementById("checkloggedin<?php echo $otherchatuser; ?>").style.marginLeft = '5px';
}
else
{
document.getElementById("checkloggedin<?php echo $otherchatuser; ?>").innerHTML = '';
}
}, 4000);
</script>
This is my code, which gets users who are logged in and also does other things. The problem that I am having occurs on this line:
$data8 = mysql_query("SELECT * FROM loggedin WHERE username='$otherchatuser' and time > '$subtractlogintime'");
The query successfully gets users from the database, but seems to be ignoring the "and time > '$subtractlogintime'");" part of the query. I have no idea why this is occurring and anyone who could possibly tell me what I have forgotten would be extremely appreciated. Thanks.
TIME is a reserved keyword in MySQL because of the TIME datatype. If it's not crashing, you would probably better off backticking your "TIME" keyword to refer to the field time.
$data8 = mysql_query("SELECT * FROM loggedin WHERE username='$otherchatuser' and `time` > '$subtractlogintime'");
Also note that, this code COULD be prone to SQL injection but we can't be sure without seeing the full code...
Related
I am trying to make this program where I can delete a thread if I am logged in. Now I already have the button linked and everything, I have it doing multiple tasks when pressed, but it seems to not run the SQL query I want it to. Now I have a variable called $forumid which is set in the URL and retrieved using $_GET['forumid'];
I know this is setting properly, because I have done echo $forumid; and its been correct. But there is one line of code that doesn't run for some reason, and that is:
$db->query("DELETE FROM threads WHERE id='$forumid'");
Now when I remove the WHERE clause, it works, but it wipes out the entire table. So I now know that the problem is the WHERE clause, I just can't find out why it is the issue. I am fairly new to PHP so please forgive my ignorance. But if anyone is able to see the issue, please tell me. Thank you.
[EDIT: COMPLETE CODE]
<?php
require 'connect.php';
session_start();
$forumid = $_GET['forumid'];
$title;
$body;
$by;
$loggedAsAuthor;
?>
<html>
<head>
<title>Legend Factions - View Forum</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="header">
Home
Forum
Vote
Donate
Members
</div>
<div id="content">
<div id="divider">
<?php
if ($result = $db->query("SELECT * FROM threads")) {
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $forumid) {
$title = $row['title'];
$body = $row['words'];
$by = $row['by'];
if ($_SESSION['sess_username'] == $by || $_SESSION['sess_username'] == "admin") {
$loggedAsAuthor = true;
}
}
}
}
echo '<h2>', $title, '</h2><br/><label>By: ', $by;
if (isset($loggedAsAuthor)) {
echo '<form action="viewForum.php" method="post">
<br/><input type="submit" name="delete" value="Delete Thread"/>
</form>';
}
$delete = $_POST['delete'];
if (isset($delete)) {
$db->query("DELETE FROM threads WHERE id=$forumid ");
//header("Location: forum.php");
}
?>
<hr/>
<?php
echo $body;
?>
</div>
</div>
</body>
</html>`
You need to modify your sql query as like :
$db->query("DELETE FROM threads WHERE id= $forumid "); // removed single quotes
Hope it works for you now.
You can try this way, Hope it will help
$qry = "DELETE FROM threads WHERE id= $forumid ";
$db->query($qry);
Your query seems to be correct.
If $_GET['forumid'] is a string, do :
$db->query("DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']));
If $_GET['forumid'] is numeric, do :
$db->query("DELETE FROM threads WHERE id=".(int)$_GET['forumid']);
In any case, string syntax should work, because string will be cast to integer by mysql.
To debug, do :
echo "DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']) ;
And give us the result, or directly paste it into phpMyAdmin to see the error.
You should also add this line at the top of your script to see all errors :
error_reporting(E_ALL) ;
ini_set('display_errors', true) ;
if(isset($_GET['forumid']) && !empty($_GET['forumid'])){
$qry = "DELETE FROM threads WHERE id= '" . mysql_real_escape_string ($_GET['forumid']) . "'";
}
or use active record
$this->db->where('id', $forumid );
$this->db->delete('threads ');
Either integer or string syntax in MySQL should work if the threads id is an integer. What I see that could be happening is:
1) $forumid does not have the value you think it has?
To check it, var_dump the variable right before the delete query:
var_dump($forumid); die;
2) The table id column is not named "id"?
Check the database schema, to check if the column has the name you think it should have. In mysql CLI:
desc threads;
i am having problem of see who's online and don't have any idea how to see who's online.what i am doing is updating mysql database using time(); whenever user log in or refreshes the page.
Then, lastactivity gets filled with epochtime for eg : 1387806657 or 1287373415.
After that i select the lastactivity from database and use this condition but nothing happens.
<?
$result = mysql_query("SELECT lastactivity FROM users WHERE lastactivity!=0");
while($rahul = mysql_fetch_assoc($result)){
$last = $rahul['lastactivity'];
echo $last;
}
?>
</br>
<?
if ($result < time()-3600)
{
$hello = mysql_num_rows($result);
echo $hello;
}
else
{
echo "ERROR!";
}
?>
You could decide that any acticity in a 30 second interval from now means "online"
$early = time()-30;
$res = mysql_query("SELECT username,lastactivity FROM users WHERE lastactivity > $early") or die( mysql_error() );
while( $row = mysql_fetch_array($res) )
{
echo $row['username'].' is online.<br>';
}
How about going to the source and parsing or watching your Apache log to see which pages are being loaded?
Well it's been my very first initiative to build a dynamic page in php. As i'm a newbie in php, i don't know much about php programming. i've made a database named "dynamic" and it's table name "answer" after that i've inserted four fields namely 'id', 'A1','A2', 'A3'.
I inserted the value in id=1 which are A1=1,A2 and A3-0,
In id=2, i have inserted A1=0, A2=1, A3=0
In id-3, i have inserted A1 and A2=0 A3=1
So now what i wanted is whenever i will click on the link of id=1 then it will display the content of id=1 and so on...
What i've done so far are:-
$conn= mysql_connect("localhost","root", "");
$db= mysql_select_db("dynamic", $conn);
$id=$_GET['id'];
$sql= "select * from answer order by id";
$query= mysql_query($sql);
while($row=mysql_fetch_array($query, MYSQL_ASSOC))
{
echo "<a href='dynamic.php?lc_URL=".$row['id']."'>Click Here</a>";
if($row['A1']==1)
{
echo "A1 is 1";
}
else if($row['A2']==1)
{
echo "A2 is 1";
}
else if($row['A3']==1)
{
echo "A3 is 1";
}
else {
echo "Wrong query";
}
}
?>
When i've executed this codes then it is showing me the exact id and it is going to the exact id but the values has not been changing..
I want whenever i will click on the id then it will display the exact value like if i click on id=2 then it will echo out "A2 is 1" nothing else....
Can anyone please help me out?
I also have noticed about
$id=$_GET['id'];
what is it and how to use it. Can anyone explain me out..
Thanks alot in advance:)
It may be best to start here to get a good understanding of php, before diving so deep. But to answer the specific questions you asked here...
The php $_GET variable is defined pretty well here:
In PHP, the predefined $_GET variable is used to collect values in a
form with method="get".
What this means is that any parameters passed via the query string (on a GET request) in the URL will be accessible through the $_GET variable in php. For example, a request for dynamic.php?id=1 would allow you to access the id by $_GET['id'].
From this we can derive a simple solution. In the following solution we use the same php page to show the list of items from the answer table in your database or single row if the id parameter is passed as part of the url.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer';
if ($_GET['id']) {
$query .= ' WHERE id = '.$_GET['id'];
} else {
$query .= ' ORDER BY id';
}
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else if ($res->num_rows == 1) {
// Display Answer
$row = $res->fetch_assoc();
echo '<h3>Answer for '.$row['id'].'</h3>';
echo '<ul>';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'</li>';
}
echo '</ul>';
}
?>
</body>
</html>
OK, this might not be exactly what you are looking for, but it should help you gain a little better understanding of how things work. If we add a little javascript to our page then we can show/hide the answers without using the GET parameters and the extra page request.
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer ORDER BY id';
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'';
echo '<ul id="answers_'.$row['id'].'" style="display:none;">';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
echo '</li>';
}
echo '</ul>';
}
?>
<script>
function toggleAnswers(answer) {
$('#answers_' + answer).toggle();
}
</script>
</body>
</html>
There are many more solutions, each more complicated that what I've presented here. For example we could set up an ajax request to load the answers into the list page only when an item is clicked. My advice is to go through some beginner tutorials on php and look at some of the popular PHP frameworks: Zend, CodeIgniter, CakePHP, etc. Depending on what you overall goal is, one of these might really help you get there faster.
Be warned that the code provided here is only an example of how to accomplish what you were asking. It definitely does not follow all (if any) best practices.
I am doing a project where I want a person to enter the name of any artist/band into a text box where it will seach my mysql database for the event information and display the results/content on another page. The code below is within my index.php where it should get the information from search.php (below also). I've looked all over and I'm not sure why it's not working and I can't figure out what to do. Help would be great! (I really need to pass this class!) :)
(index.php)
<form name="search" action="search.php" method="get">
<div align="center"><input type="text" name="q" />
<p><input type="submit" name="Submit" value="Search" /></p>
</form>
(search.php)
<?php
//Get the search variable from URL
$var=#&_GET['q'];
$trimmed=trim($var); //trim whitespace from the stored variable
//rows to return
$limit=10;
//check for an empty string and display a message.
if($trimmed=="")
{
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var))
{
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "select * from events where artist_name like \"%trimmed%\" order by date";
$numresults=mysql_query($query);
$numrows=mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0)
{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank\" title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row=mysql_fetch_array($result)) {
$title = $row["artist_name"];
echo"$count.) $title";
$count++;
}
$currPage = (($s/$limit) + 1;
echo"<br />";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
print" <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news = $s+$limit;
echo " Next 10 >>";
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Your where clause is goofy...try changing it to:
WHERE artist_name like '%$trimmed%'
just putting trimmed will be interpreted literally as the string "trimmed". However, using the variable $trimmed in your double-quoted string will give the actual variable's value.
$query = "select * from events where artist_name like '%$trimmed%' order by date";
In order to use the variable $trimmed in a query, escape it first. Otherwise, your script will be vulnerable to SQL injection attacks, and attackers will be able to run almost any query against your database. This problem is exacerbated by the fact that you are connecting to MySQL as root. Never ever do this in a production environment.
Also, to expand a variable in a string, you should include the $ character before the variable name.
$trimmed = trim($var);
$escaped = mysql_real_escape_string($trimmed);
$query = "select * from events where artist_name like \"%$escaped%\" order by date";
Your code still looks all over the place. I think the main reason it wasn't working was the mixing of " and '. You need to escape variables before you use them in your queue. mysql_real_escape_string is the lowest form of escaping you should be using. I'd recommend you have a look at PDO though.
<?php
//Get the search variable from URL
$var = $_GET['q'];
$trimmed = mysql_real_escape_string(trim($var)); //trim whitespace and escape the stored variable
//rows to return
$limit = 10;
//check for an empty string and display a message.
if($trimmed == "") {
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var)){
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "SELECT * FROM events WHERE artist_name LIKE %$trimmed% ORDER BY DATE";
$numresults = mysql_query($query);
$numrows = mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0){
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank"\ title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row = mysql_fetch_array($result)) {
$title = $row['artist_name'];
echo $count.' '.$title;
$count++;
}
$currPage = (($s/$limit) + 1;
echo "<br>";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
echo ' <a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'"><<';
echo 'Prev 10</a> ';
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news=$s+$limit;
echo ' Next 10 >>';
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo '<p>Showing results '.$b.' to '.$a.' of '.$numrows.'</p>';
?>
You are missing a $ symbol. I think
$var=#&_GET['q'];
should probably be
$var=#$_GET['q'];
unless you really want a reference, in which case it should be this: (the error suppression is not needed at this point if you want a reference, but you should check $var is set before trying to access it)
$var=& $_GET['q'];
I would be tempted to write it a bit more like this.
if (!isset($_GET['q'])) {
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
$trimmed = trim($_GET['q']);
if($trimmed=="") {
echo"<p>Please enter a name.</p>";
exit;
}
Also as Chad mentioned, an sql injection would be simple since you arent cleaning input before performing DB actions with it.
try adding
foreach($_REQUEST as $param => $value)
{
$_REQUEST[$param]=mysql_real_escape_string($value);
}
This way you escape all the user input so the user cant tamper with the db. Read more about this method and sql injection in the docs here:
http://us2.php.net/mysql_real_escape_string
Hopefully this will be the last question I need to ask about this..lol.. I cant be too far of the working solution(hopefully..lol). In reference to this question:
Pass data to database using javascript Onclick
I am trying to pass a value to the database using javascript. Below is the code i am using. And just for visual aid, Ive included a screenshot of what this outputs. Hopefully it will help to explain what im trying to achieve also. The problem im having is the javascript "Vote" link pretty much does nothing...lol... u click it, and nothing happens. Preferably i would like the links text to simply change to "You Voted!" once the link has been clicked, and data sent/recieved, but an alert will be fine, as long as i can get this to work and update the database.
Thanks everyone:)
<?php if(isset($_POST['score'])) {
mysql_query("INSERT INTO score (score_count) VALUES ($_POST[score])");
} $user_id = uid();
$m = mysql_query("SELECT * FROM friends WHERE friend_user_id1 = '$user_id' AND friend_status != '0' LIMIT 15");
while ($t = mysql_fetch_array($m))
{
$fid = $t[friend_user_id2];
$f = mysql_query("SELECT * FROM users WHERE user_status != '' AND user_status_date != '0' AND user_id = '$fid' ORDER BY user_status_date ASC LIMIT 15") or die(mysql_error());
while ($rows = mysql_fetch_array($f))
{
$date = parse_date($rows[user_status_date]);
echo "<div style='margin: 5px;'><table><tr><td valign='top' style='width:55px;'><a href='page.php?id=$rows[user_username]'>";
_photo($rows[user_id]);
echo '</a></td><td valign="top"> <b>'.$rows[user_username].'</b> - <span style="font-size:7pt;">'.$date.'</span><span style="font-size:7pt;"> - Vote</span>
<br />'.$rows[user_status].'</td><td valign="top"></td></tr></table></div>';
}
}
?>
<script type="text/javascript">
function updateScore(answer, correct) {
if (answer == correct) {
$.get('index.php', {'score': '1'}, function(d) {
alert('Vote Accepted: ' + d);
});
}
}
</script>
Outputs:
alt text http://www.freeimagehosting.net/uploads/a7185475b8.png
Wow, where do I begin. Ok, I fixed up your code. Here's a list of the changes
Formatted code for legibility (you need some serious discipline here)
Sanitized inputs before using them in queries (prevents SQL injection)
Added string delimiters to associative array key lookups (prevents E_NOTICE errors)
Escaped potentially dangerous values before printing as HTML (prevents XSS)
Removed awkward echo statements and changed to HTML mode for large output strings instead
Updated javascript to use $.post() instead of $.get() since you read from the $_POST array at the top of the script.
Here's the code:
<?php
if ( isset( $_POST['score'] ) )
{
$result = mysql_query( "INSERT INTO score (score_count) VALUES (" . mysq_real_escape_string( $_POST['score'] ) . " )" );
echo $result ? 'Vote Succeeded' : 'Vote Failed: ' . mysql_error();
exit;
}
$user_id = mysql_real_escape_string( uid() );
$m = mysql_query( "SELECT * FROM friends WHERE friend_user_id1 = '$user_id' AND friend_status != '0' LIMIT 15" );
while ( $t = mysql_fetch_array( $m ) )
{
$fid = mysql_real_escape_string( $t['friend_user_id2'] );
$f = mysql_query( "SELECT * FROM users WHERE user_status != '' AND user_status_date != '0' AND user_id = '$fid' ORDER BY user_status_date ASC LIMIT 15" ) or die ( mysql_error() );
while ( $rows = mysql_fetch_array( $f ) )
{
$date = parse_date( $rows['user_status_date'] );
?>
<div style="margin: 5px;">
<table>
<tr>
<td valign="top" style="width:55px;">
<a href="page.php?id=<?php echo escapeForHtml( $rows['user_username'] ); ?>">
<?php _photo( $rows['user_id'] ); ?>
</a>
</td>
<td valign="top">
<a href="page.php?id=<?php echo escapeForHtml( $rows['user_username'] ); ?>" class="blue">
<b><?php echo escapeForHtml( $rows['user_username'] )?></b>
</a> - <span style="font-size:7pt;"><?php echo escapeForHtml( $date )?></span>
<span style="font-size:7pt;"> - Vote</span>
<br /><?php echo escapeForHtml( $rows['user_status'] ); ?></td><td valign="top">
</td>
</tr>
</table>
</div>
<?php
}
}
function escapeForHtml( $value )
{
return htmlspecialchars( $value, ENT_COMPAT, 'UTF-8' );
}
?>
<script type="text/javascript">
function updateScore(answer, correct)
{
if (answer == correct)
{
$.post('index.php', {'score': '1'}, function(d)
{
alert('Vote Accepted: ' + d);
});
}
}
</script>
After I got all that done, I could then clearly see that your success condition for the POST to actually take place is unknown to me. You compare answer to correct but this code snippet doesn't let me see where correct comes from. Once inside the updateScore() function I can see that answer is a reference to the HTMLAnchorElement that was clicked - but what is the source for the value sent into correct?
To be specific, I'm taking about this bolded part here
onclick="updateScore(this, correct)"
Edit!
Try this for a version of your function that updates the link after a successful vote
<script type="text/javascript">
function updateScore( answer )
{
if ( confirm( "Are you sure?" ) )
{
$.post('index.php', {'score': '1'}, function(d)
{
alert('Vote Accepted: ' + d);
$(answer).after("<span>You Voted!</span>").remove();
});
}
}
</script>
The first thing I notice, in your JavaScript code you are doing the Ajax request with $.get, and in your PHP code, you expect a POST variable if(isset($_POST['score'])).
So, if you use POST variables in the server side you should use $.post in the client side.
You're not sanitizing your inputs. Anyone, using your app or not, could send you a "score", and you'll blithely put it in your database. Or they could as easily send you a SQL injection attack, by posting with score the string "1); some attack here ; insert into score(score_count) values ( 2";