Troubleshooting "unexpected T_ENCAPSED_AND_WHITESPACE" when calling mysql_query() - php

I've made this simple logout script:
<?php
session_start();
$db_connect = mysql_connect('localhost', 'root', '*****');
if(!$db_connect)
{
die('Не може да се осъществи връзка с базата данни' . mysql_error());
}
mysql_select_db("chat", $db_connect);
mysql_query("DELETE FROM activeusers WHERE au_id = '$_SESSION['UserId']'");
mysql_close($db_connect);
session_unset();
session_destroy();
?>
But when I put session_unset() and session_destroy() at the end my editor shows an error with the mysql_query I haven't tried this yet but I think that probably written this way I empty the $_SESSION array() and thus $_SESSION['UserId'] is destroyed before the query.Am I right here and how should I do it right?

Format your mysql_query-command like this:
mysql_query("DELETE FROM activeusers WHERE au_id = '".$_SESSION['UserId']."'");
This makes sure it is properly embedded into the SQL-part of the command.

change your query to:
mysql_query("DELETE FROM activeusers WHERE au_id = '".$_SESSION['UserId']."'");

If you want to inline the variable in the string, you should do one of these:
// Enclose the variable in curly braces:
mysql_query("DELETE FROM activeusers WHERE au_id = '{$_SESSION['UserId']}'");
// Remove quotes from the element name:
mysql_query("DELETE FROM activeusers WHERE au_id = '$_SESSION[UserId]'");
See http://php.net/language.types.string#language.types.string.parsing for more information on how PHP interprets variables in strings.

Related

SQL UPDATE statment does nothing, but returns no error.

<?php
require ("db/db.php");
$c_id = ($_POST['c_id']);
$c_title = ($_POST['c_title']);
$c_content = ($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_id = $c_id, c_title = $c_title, c_content = $c_content
WHERE c_id = $c_id");
header("location: index.php");
?>
This is my code.
when the header goes to the index, nothig has changed in the fields that are presented here.
i tried to echo the variables at the "echo place" and they all returned correct,
so i know that they are POSTed to the page.
i guess the error are in the SQL UPDATE statement, but PHP does not return any error to me,
it just goes directly to the index.php.
when i try to run the SQL in phpmyadmin, whith value 1 instead of the variable, it changes all the fields to 1, so there it works.
1) You should use mysql_real_escape_string()
2) why your are updating the id of a table? you also need to change your query
3) use quotes in your php variable
Try like this:
require ("db/db.php");
$c_id = mysql_real_escape_string($_POST['c_id']);
$c_title = mysql_real_escape_string($_POST['c_title']);
$c_content = mysql_real_escape_string($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_title = '$c_title', c_content = '$c_content'
WHERE c_id = $c_id limit 1") or die(mysql_error());
header("location: index.php");
You should switch to mysqli or PDO since mysql_* are outdated and will be removed.
Just to be sure, try this code (As I don't know the variables content, I put all of those with "'"
$sql = <<<SQL
UPDATE content
SET c_id='{$c_id}', c_title='{$c_title'}, c_content='{$c_content}'
WHERE c_id='{$c_id}'
SQL;
$query = mysql_query($sql);
var_dump($query);
And if the $query returns true, put the header('Location: index.php"); again

Inserting session data to mysql database

<?php
session_start();
if (!isset($_SESSION)){
}
$total_amt=$_POST['total_amt'];
$total_seats=$_POST['total_seats'];
$boarding_point=$_POST['boarding_point'];
$_SESSION['total_amt']=$total_amt;
$_SESSION['total_seats']=$total_seats;
$_SESSION['boarding_point']=$boarding_point;
?>
<?php
require_once("config.php");
$source_point=$_SESSION['source_point'];
$destination=$_SESSION['destination'];
$datepick=$_SESSION['datepick'];
$_SESSION['total_amt']=$total_amt;
$_SESSION['total_seats']=$total_seats;
$boarding_point=$_POST['boarding_point'];
// Insert data into mysql
$sql="INSERT INTO book_seat(from, to, datepick, total_amt, total_seats, boarding_point) VALUES
'{$_SESSION['source_point']}',
'{$_SESSION['destination']}',
'{$_SESSION['datepick']}',
'{$_SESSION['total_amt']}',
'{$_SESSION['total_seats']}',
'{$_SESSION['boarding_point']}')";
$result=mysql_query($sql);
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
if(!$sql) die(mysql_error());
mysql_close();
?>
I want to insert my session variables to my database..
This is my code, there is no error happening, page is redirecting to booking_detail.php but also these session variables are not getting inserted to my database also..
From and to are reserved word,use backticks
Reserved words in Mysql
$sql="INSERT INTO book_seat(`from`, `to`, datepick, total_amt, total_seats, boarding_point) VALUES
'{$_SESSION['source_point']}',
'{$_SESSION['destination']}',
'{$_SESSION['datepick']}',
'{$_SESSION['total_amt']}',
'{$_SESSION['total_seats']}',
'{$_SESSION['boarding_point']}')";
Comment out your header(), turn on error reporting using error_reporting(-1), check mysql_error() and then fix that problem.
From now I can see that you've got syntax error in sql query because you're using from as column name which is restricted word. You have to put it in `.
remove the space from top
<?php session_start();
if this didn't work
var_dump($_SESSION) before inserting to check value exist in the session
and use die(mysql_error()); with the query
$result=mysql_query($sql) or die(mysql_error());;
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
Above code will be executed once the form is submitted if chksbmt is the name of the submit button.
It takes to that page mentioned in header before inserting.
Write all your stuff in between above curly braces, use
if(isset($_POST['chksbmt']) && !$errors)
{
//all your stuff, ex:storing in DB.
if($result){
header("location:booking_detail.php");
}
}
I hope that I've understood your problem, this will workout.
First remove quotes from all session variables like:
{$_SESSION['source_point']}
Second you're redirecting before mysql_error check, Check on results and error first and then redirect:
if (!$result) {
die(mysql_error());
}
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
1) Start session if its separate script.
2) Remove reserved keyword as suggested by #Mihai in your query.
3) In your query It should be VALUES( instead of VALUES.
4) As you are mention in your comment leaving_from not inserting into Db.
Because in your script you have not assign session value for $_SESSION['source_point'] .
In your script will be :-
<?php
session_start();
if (!isset($_SESSION)){
}
$total_amt = $_POST['total_amt'];
$total_seats = $_POST['total_seats'];
$boarding_point = $_POST['boarding_point'];
$_SESSION['total_amt'] = $total_amt;
$_SESSION['total_seats'] = $total_seats;
$_SESSION['boarding_point'] = $boarding_point;
// Set here session value for $_SESSION['source_point'] as well,

syntax error on logout script?

I have a problem with my logout script. It works fine, if a user presses logout it kills the session and goes to logout.php where the user is told they've been logged out.
But when the browser cache is emptied or if the site should not be connected to the internet and if a user clicks the logout button it comes up with this error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
It fails beacause it cant set logout to '1' so i want to know how i might go about putting an else statement in somewhere to say redirect to logout.php so i don't get that horrible syntax error message.
Here's my code:
<?php
ob_start();
require('includes/_config/connection.php');
require('includes/functions.php');
?>
<?php
session_start();
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']."")
or die(mysql_error());
?>
<?php
// Four steps to closing a session
// (i.e. logging out)
// 1. Find the session
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
redirect_to("login.php?logout=1");
ob_end_flush()
?>
You have double quotes and you should be using single quotes
Change this:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']."")
To:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id='" . $_SESSION['user_id'] . "'")
PLEASE NOTE You should replace all your mysql_* functions. As of PHP 5.5.0 they are deprecated. Use something like PDO or MySQLi
Yes, there is something wrong with your quotes: As long as the user_id is an integer value you could do it like this:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']);
In case it is a string, switch to single quotes:
$result = mysql_query('UPDATE ptb_users SET user_online="Offline" WHERE id="'.$_SESSION['user_id'].'"');
You can't call session_start() after output is sent- are your requires outputting anything?
Also ensure that $_SESSION['user_id'] actually has a value; print_r($_SESSION)

location header syntax error

Firstly, I got a database of which I labelled different id for different content. However, I also made a comment box, of which my comments are all numbered by id=1,2,3... so whenever I submit a comment, it is able to link it back to the correct id I got earlier (not the comment box id), i.e. if I entered in www.example.com/synopsis?id=1, I will go back there. However, I have a delete.php file which is linked to reload.php file, whereby the page is reloaded. From this, it is unable to go back to the synopsis?id=1, instead it's just synopsis?id=
Here is my code for the submit comment button
<form action="synopsis.php?id=<?php $id =$_GET["id"]; echo $id; ?>" method="POST">
and this works.
Here is the reload.php file, which doesn't work, and I want it to be back to synopsis?id=1 everytime I hit delete
<?php
$id=$_GET['id'];
$link = mysql_connect("localhost", "root", "");
$refresh = mysql_query("SELECT id FROM dvd where id=$id",$link);
$row = mysql_fetch_assoc($result);
header("Location:synopsis.php?id=<?php $id =$_GET["id"]; echo $id; ?>");
?>
Please help
Correct string concatenation:
header("Location:synopsis.php?id=" . $id);
You already set the $id variable, you don't need to set it again
$id=$_GET['id'];
$link = mysql_connect("localhost", "root", "");
$refresh = mysql_query("SELECT id FROM dvd where id=$id",$link);
$row = mysql_fetch_assoc($result);
header("Location:synopsis.php?id=". $id);
Duplicate of quotes syntax errors?
Anyways :
<?php
$id=$_GET['id'];
$link = mysql_connect("localhost", "root", "");
$refresh = mysql_query("SELECT id FROM dvd where id=$id",$link);
$row = mysql_fetch_assoc($result);
header("Location:synopsis.php?id=".$_GET['id']);
?>
The <?php is used to switch from HTML to PHP mode, but in this code you're already in PHP mode:
header("Location:synopsis.php?id=<?php $id =$_GET["id"]; echo $id; ?>");
It's also good practice to escape variables when you build a new query string:
header("Location: synopsis.php?" . http_build_query(array(
'id' => $_GET['id'],
)));

jQuery - Save to SQL via PHP

This is probably easy for you guys, but I can't understand it.
I want to save the filename of an image to it's own row in the SQL base.
Basically, I log on to the site where I have my own userID.
And each user has its own column for background images. And the user can choose his own image if he wants to. So basically, when the user clicks on the image he wants, a jquery click event occurs and an ajax call is made to a php file which is supposed to take care of the actual update. The row for each user always exist so there's only an update of the data that's necessary.
First, I collect the filename of the css property 'background-image' and split it so I get only the filename. I then store that filename in a variable I call 'filename' which is then passed on to this jQuery snippet:
$.ajax({
url: 'save_to_db.php',
data: filename,
dataType:'Text',
type: 'POST',
success: function(data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
And this is the php that saves the data:
<?php
require("dbconnect.php");
$uploadstring = $_POST['filename'];
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
Basically, each user has their own ID and this is called 'brukerID'
The table everything is in is called 'brukere' and the column I'm supposed to update is the one called 'brukerBakgrunn'
When I just run the javascript snippet, I get this message box in return where it says:
Background changed to:
Warning: session_start() [function.session-start]:
Cannot send session cache limiter -
headers already sent (output started
at
/var/www/clients/client2/web8/web/save_to_db.php:1)
in
/var/www/clients/client2/web8/web/access.php
on line 3
This is dbconnect.php
<?php
$con = mysql_connect("*****","******","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("****", $con);
require("access.php");
?>
And this is access.php:
<?php
// Don't mess with ;)
session_start();
if($_REQUEST['inside']) session_destroy();
session_register("inside");
session_register("navn");
if($_SESSION['inside'] == ""){
if($_POST['brukernavn'] and $_POST['passord']){
$query = "select * from brukere where brukerNavn='" . $_POST['brukernavn'] . "' and brukerPassord = md5('" . $_POST['passord'] ."')";
$result = mysql_query($query);
if(!$result) mysql_error();
$rows = #mysql_num_rows($result);
if($rows > 0){
$_SESSION['inside'] = 1;
$_SESSION['navn'] = mysql_result($result,"navn");
$_SESSION['id'] = mysql_result($result,"id");
Header("Location: /");
} else {
$_SESSION['inside'] = 0;
$denycontent = 1;
}
} else {
$denycontent = 1;
}
}
if($denycontent == 1){
include ("head.php");
print('
<body class="bodylogin">
content content content
</body>
');
include ("foot.php");
exit;
}
?>
Big security issue!
You didn't quote and escape the input to the MySQL query. I could easily hack the end, stack another query, and delete your entire database!
Also, you're missing the ending parenthesis at the end of mysql_query().
mysql_query("UPDATE brukere SET brukerBakgrunn = $uploadstring WHERE brukerID=" .$_SESSION['id'] ."";
should be
mysql_query("UPDATE brukere SET brukerBakgrunn = $uploadstring WHERE brukerID=" .$_SESSION['id']);
closing parenthesis is missing and the quotes ("") are useless.
Read about SQL injection in order to make your application safe.
EDIT:
<?php
require("dbconnect.php")
?>
<?php
This code sends (the part between ?> and <?php) a newline to the output (it's the same as echo "\n") which is not allowed if you want to write to a session variable consequently.
Remove the empty line before session_start():
?>
<?php
The original error is due to a missing semicolon on the require line.
As others have said, you need to learn about sql injection and using placeholders. Get out of the habit of using submitted data without using placeholders or escaping first.
<?php
//require_once("dbconnect.php");
$uploadstring = $_REQUEST['filename'];
$db_pswd = 'xxx-xxx-xxx';
$db_user = 'john_doe';
$db_table = 'my_table';
$con = mysql_connect( 'localhost' , $user , $pswd );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db( $db_table , $con );
mysql_query(" UPDATE brukere SET brukerBakgrunn = '".$uploadstring."'
WHERE brukerID = '".$_SESSION['id']."' ");
mysql_close($con);
?>
I think you need to use a fresh code! yours is compromised! ;-))
you forgot the closing ')' in your mysql_query line !
mysql_query("UPDATE brukere SET brukerBakgrunn = $uploadstring WHERE brukerID=" .$_SESSION['id'] );
You don't need the ."" at the end of your query too.
require("dbconnect.php")
should be
require("dbconnect.php");

Categories