Unable to alter SQL using PDO statement - php

if (isset($_GET['ResetPassword'])) {
$name = $_GET['name'];
$sql = "ALTER LOGIN $name WITH PASSWORD=N'Nico1234!'";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':name', $_GET['name'], PDO::PARAM_STR);
$stmt->execute();
}
Hi guys I cant alter the password of a certain name(user) Where the name is from get (Selected from the sql).
Thanks for the help.

ALTER TABLE Statements are used for changing the schema of a Table like adding a Column or FOREIGN KEYS.
Are you trying to make an UPDATE Statement? The right query would be:
"UPDATE Login SET PASSWORD='Nico1234!' WHERE name=:name"
If you want to add the $_GET['name'] Parameter to the statement, you have to use :name anywhere inside it.

If you want to change the properties of a SQL Server login account, use ALTER LOGIN.
The problem here will be the parameter in your statement.
Table and column names cannot be replaced by parameters in PDO. I'm not sure, but I think that it's the same for login names.
So, in this case, you should use statement without parameters, escape special characters and sanitize the data manually.
As a note, when you want to use a parameter, the correct syntax for a placeholder is :name or ?, not $name.
<?php
...
try {
# SQL Authentication
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
# Windows Authentication
#$conn = new PDO("sqlsrv:server=$server;Database=$database");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
...
try {
$name = $_GET['name'];
$password = 'Nico1234!';
# Escape special characters and do some check for $name and $password values
$stmt = $conn->prepare("ALTER LOGIN $name WITH PASSWORD = N'$password'");
$stmt->execute();
} catch( PDOException $e ) {
die("Error executing query: ".$e->getMessage() );
}
...
?>
ALTER LOGIN needs permissions to execute correctly. If you use Windows authentication, then the Web server's process identity or thread identity (if the Web server is using impersonation) is used to connect to the SQL Server. Use next script for more information (change between SQL and Window authentication):
<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'uid';
$pwd = 'pwd';
# PDO Connection
try {
# SQL authentication
#$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
# Windows authentication
$conn = new PDO("sqlsrv:server=$server;Database=$database");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
#
try {
$stmt = $conn->query("SELECT 'SUSER_SNAME' AS [NAME], CONVERT(nvarchar(128), SUSER_SNAME()) AS [VALUE]");
# Data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC) ){
echo $row['NAME'].": ".$row['VALUE']."</br>";
}
} catch( PDOException $e ) {
die( "Error executing query".$e->getMessage() );
}
#
$stmt = null;
$conn = null;
?>

Related

Unable to update data in MySQL using PHP PDO Prepared

This is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=site", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("UPDATE site_users SET users_email_verified = :users_email_verified WHERE users_email = :users_email ");
$stmt->bindParam(':users_email_verified', $users_email_verified,PDO::PARAM_STR);
$stmt->bindParam(':users_email',$_GET["email"],PDO::PARAM_STR);
$users_email_verified = "yes";
$stmt->execute();
echo "done";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
But it does not update the record.
But If I write the email directly inside $user_email variable (manually), like this
$users_email = "xyz#example.com";
Then the code works.
I do not understand why? How to fix it?
You have set the binding to be INTEGERS instead of STRINGS here:
$stmt->bindParam(':users_email_verified', $users_email_verified,PDO::PARAM_INT);
$stmt->bindParam(':users_email',$_GET["email"],PDO::PARAM_INT);
You should use PDO::PARAM_STR instead.
It also appear that you're not reporting errors, so you should check your web server's error logs for additional information.

mySql database connecting to wrong server

I have been trying to setup a Sql database, but I can't get it to connect in php. here's what my code looks like:
$conn = mysql_connect("my_sql_here.net","root",'my_password_here');
print $conn;
mysql_select_db("my_database",$conn);
$created = mysql_query("SELECT * FROM `inventory`);
if(!$created) {
print "error: ";
print mysql_error();
}
print json_encode($created);
mysql_close($conn);
When I run this code, I get:
error: Access denied for user 'dom710'#'localhost' (using password: NO)false
Why is it tryng to connect to localhost? and why is trying to use root as the password?
I am super confused.
Consider using PDO to make a connection:
// Establish a connection
$host = 'my_sql_here.net';
$name = 'my_database';
$user = 'root';
$pass = 'my_password_here';
$dsn = "mysql:dbname=$name;host=$host;charset=utf8";
$conn = new PDO($dsn, $user, $pass);
// Perform your query
$query = 'SELECT * FROM `inventory`';
$statement = $conn->prepare($query);
$statement->execute();
$resultSet = $statement->fetchAll();
// Do stuff with your $resultSet
You have configured safe mode. This is why it tries to connect to localhost.
https://dev.mysql.com/doc/apis-php/en/apis-php-function.mysql-connect.html
$server "In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used."
$username "In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used."
And as someone stated in comments you shouldn't use this function because it's deprecated.

How to fix server error 500 when executing PHP script?

I am trying to insert into a database through PHP. However, when I connect to the PHP file I get server 500 error. Would anyone be able to spot what I am doing wrong?
<?php
include 'db-security.php';
function db_login()
{
$userName = filter_input(INPUT_POST, "userName");
$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$statement = $link->prepare("INSERT INTO user(username, password)
VALUES($userName, $password)");
//execute the sql statement.
$statement->execute();
}
db_login();
?>
Updated:
I have discovered the error occurs when i add filer_input or $_post to the php.
<?php
include 'db-security.php';
function db_login() {
global $conn;
// use my eaxmple to filter input to get the data out of the form, because security.
//$userName = filter_input(INPUT_POST, "userName");
$userName = $_POST['userName'];
$password = $_POST['password'];
//$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$stmt = $conn->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
//execute the sql statement.
}
db_login();
?>
db-security.php
<?php
include_once 'conf.php';
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $conn;
// Try and connect to the database, if a connection has not been established yet
if(!isset($conn)) {
// Load configuration as an array. Use the actual location of your configuration file
try
{
$conn = new PDO("mysql:host=localhost;port=3307;dbname=database", DB_USERNAME,DB_PASSWORD);
// stores the outcome of the connection into a class variable
$db_msg = 'Connected to database';
}
catch(PDOException $e)
{
$conn = -1;
$db_msg = $e->getMessage();
}
//$conn = new PDO(DB_HOST,DB_USERNAME,DB_PASSWORD , MAIN_DB);
}
}
db_connect();
?>
Where is $link defined? In 'db-security.php'? If yes then you have a variable scope problem. Just pass $link in the function call. This would have to be done for all functions.
define function as = function db_login($link)
call function like = db_login($link);
EDIT:
Don't use a function for 'db-security.php' it should be like this:
<?php
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
This is not complete code, just a sample. Now $conn is in the global variable scope and using global in the functions will work. Or just pass $conn to the function and not use global at all.
EDIT2:
Below are the working sample scripts. You need to change some information to match your setup. I'm not sure why the function is called db_login() since the function actually adds the user/password into the 'user' table.
conf.php
<?php
define('DB_USERNAME', 'test');
define('DB_PASSWORD', '123456');
?>
db-security.php
<?php
include_once 'conf.php';
try
{
$conn = new pdo("mysql:host=localhost; dbname=test; charset=utf8", DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
die('Unable to connect to database!');
}
?>
main script
<?php
include 'db-security.php';
function db_login()
{
global $conn;
$userName = $_POST['userName'];
$password = $_POST['password'];
$stmt = $conn->prepare("INSERT INTO user(username, password) VALUES(:usrname, :pswd)");
$stmt->bindParam(':usrname', $userName);
$stmt->bindParam(':pswd', $password);
$stmt->execute();
}
db_login();
?>
So you need to bind your parameters after prepare statement
$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
I have been looking at your code and I would advice you to try a different approach. I've been wrapping my head around this subject for a while when learning PHP. Best advice i've had is that you can best try when fetching information from the DB is using a try/catch statement everytime. Sounds annoying or problematic but it easy to overlook and well written maintained code because you know every try catch block will execute or catch the error atleast.
With PDO being one of the best solutions because it can connect with multiple databases the best way to execute getting information from the Database is this:*
I am gonna give you my example of something i wrote. I don't want to write it all out in your situation because i feel that's something you can better do to learn what went wrong and i hope this gives you a step in the right direction.
database.php
$serverName = "";
$dbName = "";
$userName = "";
$password = "";
try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password);
// Set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
}
catch(PDOException $e){
echo"Connection failed: " . $e->getMessage();
exit;
}
?>
index.php Executing a simple commmand get firstName from employers
<?php
require_once 'database.php';
try
{
$sQuery = "
SELECT
firstName
FROM
employees
";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo $aRow['firstName'].'<br />';
}
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
?>
Good luck and i hope my index.php is helpful in showing you how I find is the best way momentarily to talk to the database.

try/catch in php not printing anything out

Hey Everyone it has been awhile wince I've worked with try/catch blocks but I would like to start using them again just for purpose of error handling and proper practices. My code is below,
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try {
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//if the connection fails the try/catch block will pick it up
if (!$conn) {
throw new PDOException('Fatal error on connection');
} else {
//prepare and exexcute the query to match the codes up
$stmt = $conn->prepare("SELECT email_code, active from primarydb.user WHERE email_code = ?");
$stmt->bindParam(1, $email_code, PDO::PARAM_STR, 32);
//check to make sure that the statment executes properly
if (!$stmt->execute()){
throw new PDOException("PDO ERROR ON EXECUTION:\n" . $stmt->errorInfo());
} else { //statement has not failed
//get the row count
$count = $stmt->rowCount();
//traverse the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//there can only be one!
if ($count != 1 || $row['active'] != 0) {
//generate error message
throw new PDOException("Wrong Code");
} else {
echo "working";
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->brindParam(1, 1, PDO::PARAM_INT);
$stmt->bindParam(2, $email_code, PDO::PARAM_STR, 32);
if (!$stmt->execute()) {
throw new PDOException("We're sorry but we can not update your profile at this time, plesae try again later. If this problem persists please contact customer service.");
} else {
print "Your account has now been activated and it is ready to use!";
}
}
}
}
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
I would like to know why I am not getting any of the error messages, and then how do I fix this problem so that I can avoid making the same problems again in the future. If there is something that is missing or if more information is needed please let me know. Otherwise I think it is pretty straight forward.
ADDITIONAL INFO: I have putt a message that says working at each block of if/else and the one it finally stops showing up at is when I check if($count != 1 || $row['active'] != 0)
UPDATE
<?php
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try{
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->bindParam('is', $a = 1, $email_code);
if($stmt->execute()){
print "Your account has now been activated and it is ready to use!";
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
?>
Generated new code, I don't want to get off topic, but I would like a complete solution to this problem. I am now getting the following error
Strict Standards: Only variables should be passed by reference in C:\inetpub\wwwroot\mjsite\login\complete_registration.php on line 14
SQLSTATE[HY000]: General error: 2031
Thoughts?
Please read this first line from the PDOException documentation:
Represents an error raised by PDO. You should not throw a PDOException
from your own code.
Just throw and catch regular old Exceptions. This would also catch a PDOException which inherits from it.
This also gives you a much better way to distinguish between actual exception thrown by PDO and your own exceptions. By the way, it would seem you have a number of cases where you are redundantly throwing exception when PDO would have encountered an error and thrown an exception anyway. Only the first exception will be caught, so in many of those cases, your throw would never be executed.
Also why bother with the SELECT before the update at all? YOu are basically just wasting a query because you aren't doing anything with the selected information. Perhaps just go straigth for update and handle cases where email_code doesn't exist.

PHP MYSQL if statement on PDO result

Have a look through the code below. This is supposed to check whether or not a database contains a given user. If the it does, it just returns true. If it doesn't, then it returns false.
Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! ! !
function databaseContainsUser($email, $password)
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql = 'SELECT COUNT(*) FROM wl_user
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute("USE $dbname");
}
catch (PDOException $e)
{
$error = 'Error searching for user. ' . $e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
$row = $s->fetch(PDO::FETCH_NUM);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
Any help would be appreciated
For some unknown reason you are passing "USE $dbname" string to execute.
remove that string.
Also, you are trying to catch an exception but apparently don't tell PDO to throw them.
And you are catching it only to echo a message, which is a big no-no.
I've explained the right way recently in this answer
If your problem is different, you have to ask (or better - google for this very problem).
Refer to PDO tag wiki for the proper connect options including database selection and error reporting.
Try this
try
{
$pdo = new PDO('mysql:host=localhost;dbname=yourDbName;', 'root', '',
array(PDO::ATTR_PERSISTENT => true));
$sql = 'SELECT count(*) FROM user WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();
}
This is local server example, just change yourDbName to your db name. I just run this code on my local server and it is working.

Categories