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");
Related
I am trying to send two variables from an HTML page to a PHP script but the response keeps coming back as text/html. aka, the entire code in the PHP file is being returned to the console.
My jQuery code:
$.get( //call the server
"biography_query.php", //At this url
{
field: "value",
id: decodeURIComponent(id),
name: decodeURIComponent(name)
} //And send this data to it
).done( //And when it's done
function(data)
{
console.log(data);
},"jsonp"
);
PHP code:
header('Content-Type: application/json');
//start session on server to store the users information
session_start();
// establish connection to SQL database
$con = mysqli_connect("localhost","root","","capstone") or die("Error: " . mysqli_error($con));
$id = $_REQUEST['id'];
$name = $_REQUEST['name'];
// build statement to query database and return all characters
$SQL = "SELECT real_name, alternate_identities, aliases, nicknames, place_of_birth, first_appearance FROM `character` WHERE id='$id' AND superhero_name='$name'";
// execute the statement
$sqlReturn = mysqli_query($con, $SQL);
$row = array();
while($r = mysqli_fetch_assoc($sqlReturn)) {
$row['real_name'] = $r['real_name'];
$row['alternate_identities'] = $r['alternate_identities'];
$row['aliases'] = $r['aliases'];
$row['nicknames'] = $r['nicknames'];
$row['place_of_birth'] = $r['place_of_birth'];
$row['first_appearance'] = $r['first_appearance'];
}
echo json_encode($row);
"I am using <? tags"
As per OP's wishes: (to close the question, and for future readers)
If short open tags are not enabled, you will need to either enable them, or change <? to <?php.
Here are a few articles on the subject, on Stack:
How to enable PHP short tags?
Enable PHP short open tags via .htaccess
On PHP.net:
http://php.net/manual/en/ini.core.php
hi i am developing a website and i need to delete files from a server i currently have the following code
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include($_SERVER['DOCUMENT_ROOT'] . "/Scripts/Functions.php");
top();
THis Seems To Be The Problem
$query = "SELECT * FROM 'Gallery' WHERE 'ID' = '20'";
if (!mysqli_query(connect(),$query))
{
die('Error: ' . mysqli_error(connect()));
}
else
{
$Result = mysqli_query(connect(),$query);
while ($row = mysqli_fetch_assoc($Result))
{
$file = get_local($row['Image_Location']);
unlink($file);
$query2 = "DELETE FROM Gallery WHERE ID='20'";
if (mysqli_query(connect(),$query2))
{
header("Location: http://test.co.uk/Gallery/Edit/")
}
else
{
die('Error: ' . mysqli_error(connect()));
}
}
}
bottom();
?>
after going through the code i have worked out that it is an error with the if (!mysqli_query(connect(),$query)) section yet i i cant manage to work out whats wrong.
You appear to be missing a semi-colon on this line:
header("Location: http://www.littlesaintspreschool.co.uk/Gallery/Edit/")
The first problem I spot is that you have your table surrounded by single quotes.
When referring to database elements, like,
the database name
the table name
the field name
You must use backticks ` which is located to the left of the 1 key and above tab.
The second problem I see is that you are passing a function to mysqli_query. Not knowing what the return value is for connect()... I can't exactly say that that is the problem. Regardless, you should store your connection in a variable rather than a function.
if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.
Basically I've created two php papes. One selects my entire table, and displays just date, and id number from it. Each date has a link directing to a display.php file. It pulls the ID number with it to the next display.php page. What I want to do on the display.php file is to display the entire row using that PHP.
So I know that Select * from tablename WHERE id=1 will pull that data, but how to get the ID number into there WHERE statement?
This is the main page code:
// SQL query
$strSQL = "SELECT * FROM table1";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// DATE
$strName = $row['date'];
// Create a link to display.php with the id-value in the URL
$strLink = "<a href = 'display.php?ID = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
That code links works and goes to display.php.
How would I create the link using the ID number pulling with it. Would I use a post command?
$id= Post['id']
then WHERE id = '$id'
?
TBH I did try that and got nothing. Any suggestions?
USING GET now...still not luck
I've tried the GET statement. In my address bar it shows the ID number. So I see the ID number pulling over with it. I tried even just echoing the ID to see if maybe it was just my code messing up.
<?php
$dbhost = 'localhost';
$dbuser = 'myusername';
$dbpass = 'mypw';
$dbname = 'mydbname';
$id = $_GET['id'];
mysql_connect($dbhost, $dbuser, $dbpass) or die('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbname) or die('Cannot select database. ' . mysql_error());
?>
<body>
ID #<?php echo $id ?>
</body>
</html>
<body>
ID #<?php echo $id ?>
</body>
</html>
Still no luck
So in your display file you'd do something like this
$id = $_GET['ID'];
//DO SANITIZATION ETC ON THE ID HERE TO MAKE SURE ITS SOMETHING WE EXPECTED (AN INT)
$sql = "SELECT STUFF WHERE ID = {$id}"; //FOR BREVITY SAKE DOING AWAY WITH SECURITY
So basically what your first script is doing is passing the id in the url query string, values passed here are accessible in the $_GET super globals array.
Anything you access in here and the other super globals should be treated as completely dangerous to your application. You should filter and escape the hell out of it, and then before inserting it into the database you must escape it using the correct mechanism for your database. Otherwise you leave yourself open to SQL injection attacks.
Values passed in the querystring use GET not POST.
Post is for form variables.
You should also be aware of the danger of a SQL injection attack when taking values from the querystring.
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.