The UPDATE query of Mysql setting a value to a constant always...? - php

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 {}.

Related

addslashes() no slashes when inserting to database

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.

inserting data in mysql previously defined variables

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)

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.

Using a form to update data in MySQL

Having trouble getting my form to UPDATE records in my database even after searching the web and viewing the other answers on stack-overflow.
Here is my current NON functioning code:
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
session_start();
$tablename = $_SESSION['MM_Username'];
$amount=$_POST['amount'];
$UpdateQuery = "UPDATE '" . $tablename . "' SET stock = '" . $amount . "' WHERE status = 1";
mysql_query($UpdateQuery);
}
The table i want to update has the same name as the SESSION variable MM_Username. I have a form with a textbox named amount and a Submit button that when clicked, should trigger the above code. If you need to know anything else let me know. Thanks in advance!
You're using the wrong quotes around your table name. Also, your query is open to SQL injection. Consider using PDO and bind parameters.
$UpdateQuery = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `status` = 1',
$tablename);
$stmt = $pdo->prepare($UpdateQuery);
$stmt->bindParam('amount', $amount);
$stmt->execute();
Have MySQL tell you what the problem is. Change the last line of your code to this:
if (!mysql_query($UpdateQuery)) {
echo mysql_error();
}
Print out if you are having your tablename in your session variable.
print $_SESSION['MM_Username'];
Also print out the $UpdateQuery and see how the mysql query is formed. Copy that query & try running it manually in mysql to see if the query is ok.
ADVISE: I see that you have used $_POST. This is fine, but I advise you to use $_REQUEST. This var in PHP has all $_POST & $_GET content. Sometimes one forgets to change the $_POST to $_GET or vice versa & ends up wasting his time, debuggin.
if (!mysql_query($UpdateQuery)) {
echo mysql_error()
}

String value with an apostrophe in a PHP variable email address, mysql select

I have an email address mike.o'malley#stack.com stored in a posted variable and I want a select statement in mysql to validate the existance of the email address and retrieve a password from my table.
My query gets stuck at the apostophe when it trys to execute. eg "SELECT pwd FROM tbl_users WHERE userName = '$email'";
You should use mysql_real_escape_string to quote the value.
In fact, you should use it every time you insert a value in a query, if you dont, you are not only open to errors, also to SQL Injection.
You should use it like this:
if ( get_magic_quotes_gpc() ) {
$email = stripslashes($email);
}
$quoted_email = mysql_real_escape_string($email, $db_connection);
$query = "SELECT pwd FROM tbl_users WHERE userName='".$quoted_email."'";
Edit:
If PHP has magic quotes on, all superglobals values ( values in $_GET, $_POST, ... ) are quoted with addslashes which sucks. You should consider turning it off.
Use mysql_real_escape_string, for example:
$email = mysql_real_escape_string($email);
Note this should be done regardless when using variable strings in unprepared SQL to prevent SQL injection vulnerabilities.
How about wrapping $email in PHP's mysql_real_escape_string? Sanitizing all your user generated input is a good idea..
http://us.php.net/manual/en/function.mysql-real-escape-string.php
EDIT:
Mike "\" is the MySQL escape character. Here is the MySQL 5.0's documentation on strings.
mysql_real_escape_string correctly escapes the email address as 'mike.o\'malley#stack.com'. Here is a full example:
// Connect
$link = mysql_connect('localhost', 'simeon', 'password')
OR die(mysql_error());
$db_selected = mysql_select_db('db', $link);
$email = "mike.o'malley#stack.com";
// Query
$query = "SELECT email FROM users WHERE email='".mysql_real_escape_string($email)."'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo 'email: '.$row['email']."\n"; // email: mike.o'malley#stack.com
}

Categories