I am using this code to get data from Json and insert them to mysql. However it inserts no records in the data base.
<?php
include("db.php");
$currsiteurl = 'http://graph.facebook.com/1597233119';
$graph = json_decode(file_get_contents($currsiteurl));
$id = $graph->id;
echo "id : ".$id;
echo "<br>";
$username = $graph->username;
echo "username : ".$username;
echo "<br>";
$gender = $graph->gender;
echo "gender : ".$gender;
echo "<br>";
$locale = $graph->locale;
echo "locale : ".$locale;
mysql_query("INSERT INTO users_data (id, username, gender, locale)
VALUES ('.$id', '.$username', '.$gender', '.$locale')");
?>
Can any one show me whereis the mistake ?
mysql_query("INSERT INTO users_data (id, username, gender, locale)
VALUES ('.$id', '.$username', '.$gender', '.$locale')");
You are creating a single string (with embedded variables) so the dots '.' are not required.
If either of the id or gender are number-fields then this is likely to be what prevents the data from being inserted (with the dots). (If they are numbers they don't require surrounding apostrophes either.)
In addition to what Andy G states:
You should use prepared statements to make sure the data you are receiving is properly escaped to avoid sql injection attacks: http://php.net/manual/en/pdo.prepared-statements.php
To assist debugging queries, add echo mysql_error() after your mysql_query statement to print the error (or use one of the new fangled methods mentioned in the alert here: http://us1.php.net/manual/en/function.mysql-error.php)
Related
I currently have a database with a table called rooms; which has two attributes: roomID and roomType. I have inserted data into this using MySql which is all fine. I am using PHP and MYSQL in order to show what's currently in the database on the page (which is working just fine) and then a delete.php page where I have a text field for Room ID and Room Type. I wish to delete whatever I prefer from the 'rooms' table however I keep getting the Unknown table 'roomid' in MULTI DELETE error, even though I only have the one table.
Below is my current PHP
<?php
include ('connect.php');
if(isset($_POST['roomID'])){
$roomID = $_POST['roomID'];
$roomType = $_POST['roomType'];
$sql = "DELETE FROM rooms WHERE roomID='"$roomID"' AND roomType='"$roomType"' ";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
Would appreciate any help
WARNING!
Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!
Here's the problem -
If only you had used prepared statements you wouldn't have had to worry about concatenating the variables properly. The following portion of your query line is missing the proper concatenation:
WHERE roomID='"$roomID"' AND roomType='"$roomType"'
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.
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.
The Update customer query in this code setting phno to a constant 2147483647
always instead of setting to the value submitted... i tried echoeing $phone its correct.. but its not working when im executing query....
<?php
include 'database.php' ;
$id=$_POST["customer"];
$name = $_POST["name"];
$address = $_POST["address"];
$phone = $_POST["phno"];
$sql = "UPDATE `customer` SET `phno`=$phone, `name`='$name',`address`='$address' WHERE actno=$id";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "successful";
mysqli_close($con);
?>
You set phno as INTEGER, didn't you? The maximum value of INTEGER is 2,147,483,647, so any number larger than 2,147,483,647 is out-of-range, and will be inserted as 2,147,483,647.
Change the datatype of phno to BIGINT or VARCHAR.
Also, your query is vulnerable to SQL injections, see the link below for more details.
See also:
Integer Types in MySQL
What's the best method for sanitizing user input with PHP?
I think you are trying to substitute $phone in the string,
but it wont work that way, either you split the string or use {}.
Before posting my form I am checking the database to see if there are any previous posts from the user. If there are previous posts then the script will kick back a message saying you have already posted.
The problem is that what I am trying to achieve isn't working it all goes wrong after my else statement. It is also probable that there is an sql injection vulnerability too. Can you help??4
<?php
include '../login/dbc.php';
page_protect();
$customerid = $_SESSION['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
To answer the second part of your question: yes, you're very vulnerable to SQL injection:
$sql="INSERT INTO content (customerid, ...) VALUES ('$_POST[customerid]', ...)";
^
This article explains SQL Injection and how to avoid the vulnerability in PHP.
You are missing curly brackets {}:
<?php
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>
In addition to the missing curly braces mentioned previously it looks like you're assigning in the if statement, which will cause the statement to always evaluate to true:
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
Should be:
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
Also, $checkid contains an SQL query string. I assume you intend to actually run the query and populate $checkid with something comparable to a $customerid before actually getting to the comparison.
In addition to the SQL injections (man, read a book/tutorial about that before you start!) and the missing braces after the else, you have two errors in there: First, you don't execute the $checkid query, secondly, you only have one = in the if (so you assign the value of $customerid to $checkid.
It is also probable that there is an sql injection vulnerability too.
Why "is possible"? Don't you see that yourself? Don't you write your code in a way that you avoid such issues in the first place?
Re: sql injection - any time you trust data from your users you're vulnerable. Take your INSERT statement and sanitize it.
$sql = sprintf("INSERT INTO content (customerid, weburl, title, description) VALUES ('%d','%s','%s','%s')",
$_POST['customerid'], //forced as digit
mysql_real_escape_string($_POST['webaddress']),
mysql_real_escape_string($_POST['pagetitle']),
mysql_real_escape_string($_POST['pagedescription']) );
Also, you should use apostrophes in your array keys. In double quotes, that'd be:
echo "Post data webpage title is {$_POST['pagetitle']}";
$_SESSION will clear when the browser is closed out. Therefore, I'd suggest using Cookies for a definite way.
I've updated your code as follows:
include '../login/dbc.php';
page_protect();
$customerid = $_COOKIE['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}else{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
die('Error: ' . mysql_error());
else
echo "1 record added";
}
If you are worried about injection add this tidbit prior to your insert query:
foreach($_POST as $key=>$value){
$_POST[$key] = addslashes($value);
}