I want to update MySQL database by below code, but it doesn't work why?
<?php
mysql_connect("localhost","root","");
mysql_select_db("timer");
$update=$_COOKIE['name'];
mysql_query("UPDATE user SET password='2' WHERE username=$update");
?>
String values should be quoted: MySQL String Literals.
mysql_query("UPDATE user SET password='2' WHERE username='$update'");
$dsn = 'mysql:dbname=timer;host=127.0.0.1';
$user = 'root';
$password = '';
$update=$_COOKIE['name'];
$query = 'UPDATE user SET password='2' WHERE username=(?)';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->prepare( $query )->execute( array($query) );
} catch (PDOException $e) {
echo 'Connection failed ' . $e->getMessage();
}
Can't be sure if it works because I don't know what you have in your $_COOKIE array.
But the code should look like this.
For security, you can add some text transformation to the variable $update like addslashes or other ones.
Use prepared queries, the way you do it isn't a good practice. Check also if $update isn't empty, otherwise the query will not work, Finally, use mysqli_* functions instead of mysql_* :)
<?php
mysql_connect("localhost","root","");
mysql_select_db("timer");
$update=$_COOKIE['name'];
mysql_query("UPDATE ´user´ SET password='2' WHERE username='$update'");
?>
Try to mention the name of your table in this query like this: ´user´
Let me recommend you that if your query doesn't work then you could put the whole query in an echo (or print) to see whats wrong.
For example:
echo "mysql_query(\"UPDATE user SET password='2' WHERE username=$update\";
Related
i would really appreciate if anyone can help me out with this mysql php problem of which i have no idea how to do it.
I Have a column named = 'x'
The text of that column 'x' is = "yz,zz,zy"
I want to edit the value of the column 'x' to = "yz,zyz,zy".
Now how do i add that 'y' in the middle term between yz and zy using CONCAT.
Regards.
You haven't provided any code or an attempt for us to go off of something so I'll give you a brief way of doing it. Look up PDO here This is a really easy to follow and secure way to manipulate data in your database using php. Again as you haven't given me much to go off i'm unsure if you want to just set something at specific count of characters along OR if you want to just update the entire thing, SO i'll help you with the latter as it will help give you some base understanding.
Please read into PDO further as this is just an example further down the line and will not run if you just blindly copy and paste it in.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE table SET x='yz,zyz,zy' WHERE id= 1"; // No clue if you've even given anything IDs
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As you haven't really provided any Schema of the table you are updating this is the best I could provide based off of what you have given me.. try to include as much information as possible as I'm unsure if this is what you even want
I have a simple question. I'm not too good at programming yet but is this safe and correct?
Currently I am using functions to grab the username, avatars, etc.
Looks like this:
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
config.php ^^
function getUsername($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT username FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$name = $stmt->fetch();
return $name["username"];
}
function getProfilePicture($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$image = $stmt->fetch();
return $image["profilepicture"];
}
Is this correct and even more important, is this safe?
Yes, it's safe with respect to SQL injections.
Some other answers are getting off topic into XSS protection, but the code you show doesn't echo anything, it just fetches from the database and returns values from functions. I recommend against pre-escaping values as you return them from functions, because it's not certain that you'll be calling that function with the intention of echoing the result to an HTML response.
It's unnecessary to use is_int() because MySQL will automatically cast to an integer when you use a parameter in a numeric context. A non-numeric string is interpreted as zero. In other words, the following predicates give the same results.
WHERE id = 0
WHERE id = '0'
WHERE id = 'banana'
I recommend against connecting to the database in every function. MySQL's connection code is fairly quick (especially compared to some other RDBMS), but it's still wasteful to make a new connection for every SQL query. Instead, connect to the database once and pass the connection to the function.
When you connect to your database, you catch the exception and echo an error, but then your code is allowed to continue as if the connection succeeded. Instead, you should make your script die if there's a problem. Also, don't output the system error message to users, since they can't do anything with that information and it might reveal too much about your code. Log the error for your own troubleshooting, but output something more general.
You may also consider defining a function for your connection, and a class for your user. Here's an example, although I have not tested it:
function dbConnect() {
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
error_log("PDO connection failed: " . $e->getMessage());
die("Application failure, please contact administrator");
}
}
class User {
protected $row;
public function __construct($userid) {
global $conn;
if (!isset($conn)) {
$conn = dbConnect();
}
$stmt = $conn->prepare("SELECT username, profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$this->row = $stmt->fetch(PDO::FETCH_ASSOC);
}
function getUsername() {
return $this->row["username"]
}
function getProfilePicture() {
return $this->row["profilepicture"]
}
}
Usage:
$user = new User(123);
$username = $user->getUsername();
$profilePicture = $user->getProfilePicture();
That looks like it would work assuming that your config file is correct. Because it is a prepared statement it looks fine as far as security.
They are only passing in the id. One thing you could do to add some security is ensure that the $userid that is passed in is the proper type. (I am assuming an int).
For example if you are expecting an integer ID coming in and you get a string that might be phishy (possible SQL injection), but if you can confirm that it is an int (perhaps throw an error if it isn't) then you can be sure you are getting what you want.
You can use:
is_int($userid);
To ensure it is an int
More details for is_int() at http://php.net/manual/en/function.is-int.php
Hope this helps.
It is safe (at least this part of the code, I have no idea about the database connection part as pointed out by #icecub), but some things you should pay attention to are:
You only need to require your config.php once on the start of the file
You only need to prepare the statement once then call it on the function, preparing it every time might slow down your script:
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. - PHP Docs
(Not an error but I personally recommend it) Use Object Orientation to help organize your code better and make easier to mantain/understand
As stated by #BHinkson, you could use is_int to validate the ID of the user (if you are using the IDs as numbers)
Regarding HTML escaping, I'd recommend that you already register your username and etc. HTML escaped.
Hy everyone, I can't wrap my head around this. I'm trying to get some data from a table using PDO. this is my code:
//in db.php I have the connection:
$host = 'localhost';
$db = 'APL';
$dbuser = '';
$pass = ' ';
try{
$conn = new PDO("mysql:host=$host;dbname=$db", $dbuser, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//in my file I have this:
$id = $_GET['id'];
$sel_sql = "SELECT * FROM users WHERE id =:id";
$stmt = $conn ->prepare($sel_sql);
$stmt -> bindParam(':id', $id);
$stmt -> execute();
$result = $stmt -> fetchAll(PDO::FETCH_ASSOC);
The problem is that print_r($result) returns '1' (just the value 1, therefore I can't access any data stored in the table) as long as $_SESSION['user'] is set.
The whole data-retrieving worked just fine if the $_SESSION['user'] is not set.
Can someone please explain why this is happening? (I'm fairly new to all this and I'm really trying to understand why some issues occur).
Thank you!
The fetchAll function should be returning either an array, or a boolean FALSE.
You report that print_r($result) is displaying an integer value of 1.
I don't see how that's possible, unless you are assigning a different value to $result. Try relocating print_r($result) to immediately follow the assignment from fetchAll.
(My suspicion is that $result is being assigned a value of 1 elsewhere in your code, before you do the print_r. If there were "Issues with php connection to MySQL database", we'd be expecting to see a PDO error of some sort.)
NOTE: I don't think PDO::FETCH_ASSOC is a defined fetch style for the fetchAll function. (fetchAll has different fetch styles than fetch.)
Just in case someone else stumbles upon this, between the $result variable and the print_r($result) I had an include_once(); statement (which was wrongly put there in the first place).
Thank you everyone for your answers.
I believe I have the syntax correct, at least according to my textbook. This is just a piece of the file as the other info is irrelevant to my problem. The table name is user, as well as the column name is user. I don't believe this to be the problem, as other sql statements work. Though it isn't the smartest thing to do I know :) Anyone see an error?
try {
$db=new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user,$db_pass);
} catch (PDOException $e) {
exit("Error connecting to database: " . $e->getMessage());
}
$user=$_SESSION["user"];
$pickselect = "SELECT game1 FROM user WHERE user='$user' ";
$pickedyet = $db->prepare($pickselect);
$pickedyet->execute();
echo $pickselect;
if ($pickedyet == "0")
{
echo '<form method="post" action="makepicks.php">
<h2>Game 1</h2>......'
Since you're seemingly using prepared statements, I'd recommend using them to their fullest extent so that you can avoid traditional problems like SQL injection (this is when someone passes malicious SQL code to your application, it's partially avoided by cleansing user inputs and/or using bound prepared statements).
Beyond that, you've got to actually fetch the results of your query in order to display them (assuming that's your goal). PHP has very strong documentation with good examples. Here are some links: fetchAll; prepare; bindParam.
Here is an example:
try
{
$db = new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user, $db_pass);
}
catch (PDOException $e)
{
exit('Error connecting to database: ' . $e->getMessage());
}
$user = $_SESSION['user'];
$pickedyet = $db->prepare('SELECT game1 FROM user WHERE user = :user');
/* Bind the parameter :user using bindParam - no need for quotes */
$pickedyet->bindParam(':user', $user);
$pickedyet->execute();
/* fetchAll used for example, you may want to just fetch one row (see fetch) */
$results = $pickedyet->fetchAll(PDO::FETCH_ASSOC);
/* Dump the $results variable, which should be a multi-dimensional array */
var_dump($results);
EDIT - I'm also assuming that there is a table called 'user' with a column called 'user' and another column called 'game1' (i.e. that your SQL statement is correct aside from the usage of bound parameters).
<?php
session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
try
{
// nothing was wrong here - using braces is better since it remove any confusion as to what the variable name is
$db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e ) // catch all exceptions here just in case
{
exit( "Error connecting to database: " . $e->getMessage() );
}
// this line is unecessary unless you're using it later.
//$user = $_SESSION["user"];
// no need for a new variable here, just send it directly to the prepare method
// $pickselect = '...';
// also, I changed it to a * to get the entire record.
$statement = $db->prepare( "SELECT * FROM user WHERE user=:user" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user', $_SESSION['user'], PDO::PARAM_STR );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );
echo $userRow->game1;
Change this user=$user with this user='$user'. Please, note the single quotes.
Moreover, you are executing the query $pickedyet->execute(); but then you do echo $pickselect; which is nothing different from the string that contains the query.
Little hints:
You've to retrieve the result of the query execution.
You're using prepared statement which are very good but you're not really using they because you're not doing any binding.
I'm setting up a blog type page for my business. Brand new to MySQL and PHP. Set up this login system. For some reason have no idea why the login is dropping. Suppose to check for errors then return 'good' through php if the email and password is right. If php returns good then it's suppose to redirect to the blog page.
Been dealing with this for a few months need desperate help please. Thank you.
Here is the php code that goes along with the jquery.
Link to test site is here.
test.toddprod.com/login
Would really appreciated the help.
Thanks
<?php
#fake mysql connection first
DEFINE ('DB_USER','usernamegoeshere');
DEFINE ('DB_PASSWORD','passwordhere');
DEFINE ('DB_HOST','hostnamehere');
DEFINE ('DB_NAME','andtheotherthinghere');
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
$db = mysql_select_db(DB_NAME, $dbc) or die('Could not select database.'.mysql_error());
$e = $_POST['email'];
$pass = $_POST['pass'];
$q = 'SELECT user_id from toddprod where email="'.$e.'" and pass= SHA1("'.$pass.'")';
$r = mysql_query($db, $q);
if( mysql_num_rows($r)==1 ){
setcookie ( 'user_id', $r);
setcookie ( 'email', '$e');
setcookie ( 'logged-in', 'true');
echo 'good';
}
else if (mysql_num_rows($r)==0) {
echo 'Your '.$e.' with password '.$pass;
};
mysql_close ($db);
?>
Umm there's a number of things I see wrong here...
First of all your query should be sanitized...
$email = mysql_real_escape_string ($_POST['email']); // escape the email
$pass = SHA1(mysql_real_escape_string ($_POST['pass'])); // escape and encrypt the pass
// now you can put it into the query safely
$query = "SELECT user_id from toddprod where email = '$email' and pass = '$pass' ";
Next you're executing the query wrong, the mysql_query function takes two arguments, the query and the database connection. You're passing the wrong arguments, you're passing the query and the result of the mysql_select_db function which is just a boolean value. So you have to $dbc not $db into that query, and even then you're passing the arguments in the wrong order. The query goes first, than the connection. So it should be...
$result = mysql_query($query, $dbc);
Next you're trying to set the return value from the mysql_query function as your cookie but that value is a resource, not the userid that you need. You have to actually read the value from the resource like this.
$row = mysql_fetch_array($result);
$userid = $row["user_id"];
setcookie('user_id', $userid);
Moving on... when you're setting the email cookie, you have the variable in single quotes, so the cookie will actually contain $e and not the actual email because single quotes store strings litterly (without parsing the variables). So you should either use double quotes, or no quotes at all. So either one of the following is fine...
setcookie('email', "$e");
setcookie('email', $e);
Last but not least, you should not have the semicolon at the end of your if-statement, and you again you need to pass the connection not the database-selection result into the mysql_close function, so it should be
mysql_close($dbc);
There, hope this gets you somewhere, try out these changes and if the problem persists i'd be happy to help you further.
Here are links that will help you out:
http://www.php.net/manual/en/function.mysql-query.php
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit:
Here, I have fixed the code according to the problems I found. Try it out, I could not test it so it might have some small syntax errors here and there, but it should give you something to compare with. Also for the future, I would suggest that you name your variables semantically/properly so it's easier for others to pickup and it will also keep you from getting confused like you were passing $db instead of $dbc into a few of your functions.
<?php
// keep the function names in lowercase, no reason, just looks better to me
define('DB_USER', 'usernamegoeshere');
define('DB_PASSWORD', 'passwordhere');
define('DB_HOST', 'hostnamehere');
define('DB_NAME', 'andtheotherthinghere');
// connect to the mysql server
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
// select the database, you don't need to store the result, it just returns true or false
mysql_select_db(DB_NAME, $conn) or die('Could not select database.' .mysql_error());
// escape the input
$email = mysql_real_escape_string($_POST['email']);
$pass = sha1(mysql_real_escape_string($_POST['pass']));
// create the query
$query = "SELECT user_id FROM toddprod WHERE email = '$email' AND pass = '$pass'";
// execute the query
$result = mysql_query($query, $conn);
$usercount = mysql_num_rows($result);
if($usercount == 1){
// read the results and get the user_id
$row = mysql_fetch_array($result);
$userid = $row['user_id'];
// set the cookies
setcookie('user_id', $userid);
setcookie('email', $email);
setcookie('logged-in', 'true');
// echo success message
echo 'good';
}elseif($usercount == 0) {
echo "You're $email with password $pass";
}
mysql_close($conn);
?>
First things first, you MUST sanitise user input with mysql_real_escape_string():
$e = mysql_real_escape_string ($_POST['email']);
$pass = mysql_real_escape_string ($_POST['pass']);
Read up a bit on SQL injection, you'll be very glad you did.
As for the main problem, could you provide a bit more context? How are you checking to see if the user is logged in?