addslashes() no slashes when inserting to database - php

For some reason addslashes is NOT adding slashes when inserting data into database. I thought I was using this right, but clearly not... When I submit data that has single or double quotes, it is just sending the exact string right in. Any ideas on how to make this work?
The code
<?php
//include db connect
include ("db_con.php");
//start session
session_start();
//set variable names
$username = $_SESSION['username'];
$entry = addslashes($_POST['entry']);
$uri = $_SERVER['HTTP_REFERER'];
//send chat
$query = mysqli_query($con, "INSERT INTO chat (username, entry) VALUES
('".$username."', '".$entry."')");
if ($query) {
header('Location: '. $uri);
} else {
echo 'Chat entry failed for an unknown reason - Please go back and try again';
}
?>

addslashes() is for escaping the string. If you got code:
$lastname = "O'Bama";
$query = "SELECT name FROM users WHERE lastname='$lastname'";
The query will produce an error because Bama will be treated as SQL statement. To prevent this you can use addslashes() so
echo addslashes($lastname); // returns O\'Bama
Now you can execute your query without any errors because your database will see value as "O'Bama".

Using addslashes() when dealing with databases is very bad practice. Since you're using PHP's mysqli extension, you should escape your data with mysqli_real_escape_string(). The PHP manual page for addslashes() explains why.

Related

When adding fields to my database i get blank data

im trying to add data to my database but this code seems to just add blank data. Any solutions would be much appreciated. Thanks in advance.
<?php
session_start();
include 'dbh.php';
$start = $_POST['starttime'];
$finish = $_POST['finishtime'];
$dat = $_POST['date'];
$id = $_POST['userid'];
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES ('$start', '$finish', '$dat')";
$result = mysqli_query($conn, $sql);
if ($result->affected_rows){
$row=$result->fetch_assoc();
echo'<pre>',print_r($row),'</pre>';
}else{
echo"didnt work";
}
//header("Location: index.php");
?>
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES (".$start.", ".$finish.", ".$dat.")";
$result = mysqli_query($conn, $sql);
Try the above if any are string values you will need to add quotation marks around them single one ('".$start."').
First of all, use var_dump() to check all $_POST variables - do they have values?
If the method of your form is "get" you should use $_GET.
Step 2. After finding the (probably missing) variables please change you SQL query, otherwise you will have big risk of injection.
You should use prepared statements everywhere dealing with database. Check manual - http://php.net/manual/ru/mysqli.quickstart.prepared-statements.php .
And, by the way, you missing execute () function in your code.

how to save in database after successful login?

i just want to add the ip address and the username after successful login this is my code. The problem is it did not continue to the profile after login but when i remove the insert query it continue to the profile what should i do ?
session_start();
if(isSet($_POST['username']) && isSet($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($db,$_POST['username']);
$password=mysqli_real_escape_string($db,$_POST['password']);
$password=md5($password);
$result=mysqli_query($db,"SELECT PatientId FROM patient WHERE PatientId='$username' AND Password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['PatientId']=$row['PatientId'];
echo $row['FirstName']. ' '.$row['LastName'];
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$query=mysqli_query($db,"insert into login_history_patient(PatientId,IP)Values('".$username.",'".$ip"')");
}
}
The first initial problem here, is that you're not checking for errors and assuming success right off the bat.
This line:
$query=mysqli_query($db,"insert into login_history_patient(PatientId,IP)
Values ('".$username.",'".$ip"')");
being modified to:
$query=mysqli_query($db,"insert into login_history_patient (PatientId,IP)
Values ('".$username.",'".$ip"')")
or die(mysqli_error($db));
would have signaled the syntax error.
http://php.net/manual/en/mysqli.error.php
Missing a concatenate '".$ip"' => '".$ip."'
You could have also used:
$result = mysqli_query($db, $query);
if (!$result)
{
throw new Exception(mysqli_error($db));
}
else{ echo "Success."; }
Ideally, using mysqli_affected_rows() will give you a better result, if the query truly was successful.
http://php.net/manual/en/mysqli.affected-rows.php
Plus, you're storing passwords using MD5 which is a very bad idea because it's old and considered broken, should this site go or is LIVE.
You should also use mysqli with prepared statements, or PDO with prepared statements.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Your users will thank you for it.
Always use properly formatted queries like this:
SELECT * FROM login WHERE id = '" . $id . "';
The last query you are executing, is half properly formed (you're missing a dot):
$query=mysqli_query($db,"insert into login_history_patient(PatientId,IP)Values('".$username.",'".$ip."')");
The . was missing after the '".$ip"'
In any language syntax of Concatenation of string with variable is important.
If you are putting variables into query make sure that the quotes start and properly, .(dot) is used to concatenate so end the string , use .(dot) put variable again use .(dot) , start the string.
"string".$variable."string continues.."
hope it helps..

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Use of header function in PHP

I'm adding a contact to my database with a form on the page add.php, the INSERT code for this form is on another page we'll call php.php page. In php.php I have a header function which I would like to have redirect the user to another page edit.php?ID=100, ID=100 being the contact that was just entered. How would I do this, do I need to do a fetch from the db before the header function and INSERT query?
<?php
if (isset($_POST['$fname'])) {
header("location: http://www.mydomain.com/contacts/edit/?ID=<? echo $row['ID]; ?>");
$connect = mysql_connect (...)
mysql_select_db ("mydb);
$ID = $_POST['ID'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sql = ("INSERT INTO contacts (fname, lname) VALUES ('$_POST[fname]', '$_POST[lname]')");
mysql_query($sql,$con) or die ("Error: ".mysql_error());
exit;
}
?>
I believe mysql_insert_id is the function you're looking for. It'll return the AUTO_INCREMENT ID of the field that was just inserted. You can then plug that into your header redirect. Just make sure to do the header redirect AFTER you insert the contact. It'll work just fine.
Code that should work:
<?php
if (isset($_POST['$fname'])) {
$connect = mysql_connect (...)
mysql_select_db ("mydb");
$ID = $_POST['ID'];
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$sql = "INSERT INTO contacts (fname, lname) VALUES ('$fname', '$lname')";
mysql_query($sql,$connection) or die ("Error: ".mysql_error());
header("location: http://www.mydomain.com/contacts/edit/?ID=".mysql_insert_id($connection));
exit;
}
?>
The code you posted was also susceptible to MySQL injections, so I mysql_real_escape_string'd your input to prevent that from happening. Always sanitize input before putting it into your query. I encourage you to look at the MySQLi functions that PHP has to offer.
You need to send the headers after the current script has done all that you want it to do. Sending headers doesn't necessarily immediately cancel the execution of that script; it can still persist for a bit, but you should do after you do your SQL calls.
The header doesn't terminate the run of the script.
If you use location redirect is a good practice to exit from the script, what you did correct.
Be aware one thing, do not put any output to the stdout before the header.
You can't embed php code in the header function (the <? echo $row['ID]; ?>). To achieve what you are trying to do, you should have the INSERT code before the header function. Then you should retrieve the ID of the contact you just entered and then call the header function, like so (assuming $id is the retrieved ID):
header("location: http://www.mydomain.com/contacts/edit/?ID=".$id);
To retrieve the ID of the last inserted row, you can use the mysql_insert_id function (reference), though it is recommended you use the mysqli version.

how can i share data between PHP pages?

I have a PHP page and I want to share some data between pages like UserID, password.
I'm learning about sessions and I'm not sure if Im using it correctly.
<?php
require_once('database.inc');
$kUserID = $_POST['kUserID'];
$kPassword = $_POST['kPassword'];
if (!isset($kUserID) || !isset($kPassword)) {
header( "Location: http://domain/index.html" );
}
elseif (empty($kUserID) || empty($kPassword)) {
header( "Location: http://domain/index.html" );
}
else {
$user = addslashes($_POST['kUserID']);
$pass = md5($_POST['kPassword']);
$db = mysql_connect("$sHostname:$sPort", $sUsername, $sPassword) or die(mysql_error());
mysql_select_db($sDatabase) or die ("Couldn't select the database.");
$sqlQuery = "select * from allowedUsers where UserID='" . $kUserID . "' AND passwordID='" . $kPassword . "'";
$result=mysql_query($sqlQuery, $db);
$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){
session_start();
session_register('kUserID');
header( "Location: link.php" );
}
}
else {
echo 'Incorrect login name or password. Please try again.';
}
}
?>
For the love of all that is holy, don't use addslashes to prevent SQL injection.
I just owned your site:
Image of your ownt site http://localhostr.com/files/8f996b/Screen+shot+2010-02-23+at+7.49.00+PM.png
Edit: Even worse.
I just noticed that you're attempt at preventing injection via addslashes, isn't even being used!
<?php
$kUserID = $_POST['kUserID'];
$user = addslashes($_POST['kUserID']); // this isn't used
$sqlQuery = "select * from allowedUsers where UserID='"
. $kUserID . "' AND passwordID='" . $kPassword . "'";
Be aware that session_register() is deprecated in favor of assigning values to the $_SESSION superglobal, e.g.
<?php
$_SESSION['hashedValue']= '437b930db84b8079c2dd804a71936b5f';
?>
Also be aware that anything stored in a session, especially in a shared-server environment, is fair game. Never store a password, regardless of whether it's hashed or encrypted. I would avoid storing a username as well. If you must use some authentication mechanism between pages using a session variable, I'd recommend using a second lookup table, e.g. logins, and store the username, login time, etc in that table. A hashed value from that table is stored in the session, and each page request checks the time in the table and the hashed value against the database. If the request is either too old or the hash doesn't match, force re-login.
All this and more is available to you in the PHP manual section on sessions.
You might also wanna rename "database.inc" to "database.inc.php", or properly setup your host to treat ".inc" as PHP:
http://www.namemybabyboy.com/database.inc
<?php
$sDatabase = 'shayaanpsp';
$sHostname = 'mysql5.brinkster.com';
$sPort = 3306;
$sUsername = 'shayaanpsp';
$sPassword = 'XXXX';
$sTable = 'allowedUsers';
?>
First, you need to put session_start() at the very beginning of your script. It also needs to go at the start of every script that uses session data. So it would also go at the top of babyRegistration.php.
Second, I would strongly recommend against using session_register() as it relies on register_globals which is off by default for security reasons. You can read more here: http://php.net/manual/en/security.globals.php. You can add/access session variables by using the $_SESSION superglobal:
$_SESSION['kUserID'] = $kUserID;
Last, not really session related, just an observation, your isset check at the top is redundant; empty will return true for an unset/NULL variable, just as you might expect.
At the top of a page
session_start();
$_SESSION['yourvarname']='some value';
then on some other page to retrieve
echo $_SESSION['yourvarname'];
// some value
Oh and about injection,use this on everything going into your db
http://us3.php.net/manual/en/function.mysql-real-escape-string.php
Just because almost everything turned into avoiding SQL injections. Escaping string is not going to save you from SQL injections. The correct way is using prepared statements.
https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

Categories