So I have a PDO and MySQL script that is used to retrieve a result based on the user's username, or screen name, in this case being e.
First, I have a function at the beginning of the file that is used to connect to the database. (it is present in a functions.php file and required at the beginning of each page, thus the globalization). This function doesn't have anything wrong with it (as far as I know).
function SQLConnect () {
// Database connection variables
$host = "localhost";
$dbname = "dropbox";
$user = "root";
$password = "ethan17458";
// Connect to the database
try {
//put $connect in global scale of document
global $connect;
// attempt to connect to database
$connect = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
// Sets error mode
$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
// Retrieves error message if connection fails
echo $e->getMessage();
}
}
This function uses PDO to connect to the database containing the user's information.
Next is the script to retrieve the user's data
// Test user in database
$test = "e";
try {
//confirms running of "try" block
echo "tried";
//database information
$host = "localhost";
$dbname = "dropbox";
$user = "root";
$password = "ethan17458";
//Prepare statement from connection function
// username_raw is "e"
//username should be e1671797c52e15f763380b45e841ec32 (md5)
$statement = $connect->prepare("SELECT `username` FROM `users` WHERE `username_raw` = ':name'");
//create placeholder for prepared statement
$statement->bindParam(":name", $test);
//make the statement fetch in an associative array
$statement->setFetchMode(PDO::FETCH_ASSOC);
//execute the prepared statement
$statement->execute();
//set $get_result to the fetched statement
$get_result = $statement->fetch();
//attempt to display the data fetched in $get_result
echo "<br />";
echo "<pre>";
//Outputs 1 for some reason
// **not working**
echo print_r($get_result);
echo "</pre>";
echo "<br />";
} catch (PDOException $e) {
//confirm running of "catch" block
echo "caught";
// echo error message
echo $e->getMessage();
}
When I run this script I get this output:
tried
1
In this output, tried is the confirmation that the "try" statement was processed, and the 1 is where I start to run into problems.
If the script was working as I would like, the script would retrieve the data e1671797c52e15f763380b45e841ec32 from the database because it is the column username where the username_raw is e, as is stated in the PDO prepared statement.
The ideal output should be
tried
e1671797c52e15f763380b45e841ec32
What am I doing wrong?
fetch() is returning false, which prints nothing to the screen. This is false because you're getting no results because you're putting single quotes around your parameter in the query, which PDO takes care of for you. Just remove the quotes around :name.
Related
My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.
i'm currently using mysqli procedure to write code which i want to change it in pdo because in mysqli i'm mysqli_escape_string whereas i dont how to change it in pdo
here is my mysqli attempt
<?php
if(isset($_GET['id1'])){
$id=$_GET['id1'];
$result=GetWordsById(mysqli_escape_string($conn,$id));//Here GetWordsById is a function calling store procedure
if(mysqli_num_rows($result)>0)
$row=mysqli_fetch_array($result);
$word=$row['word'];
$meaning=$row['meaning'];
$synonym=$row['synonym'];
$antonym=$row['antonym'];
}
?>
below is my function.php
function GetWordsByID($id){
include("conn.php");
$result=mysqli_query($conn,"CALL GetWordsById($id)");//Here GetWordsById is my store procedure
return $result;
}
Here i want to know how i can change both function and main php script calling function where i'm using mysqli_escape_string to pdo i'd appreciate some help
To PDO,
your db connection file will look like this,
<?
$servername = "localhost";
$username = "username"; // Enter your db username
$password = "password"; // Enter your db password
$dbname = "myDBPDO"; // Enter your db name
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Now comes your code,
<?
if(isset($_GET['id1'])){
$id=$_GET['id1'];
$result=GetWordsById($id);//Here GetWordsById is a function calling store procedure
if($result->fetchColumn()>0){
$row=$result->fetch(PDO::FETCH_ASSOC);
$word=$row['word'];
$meaning=$row['meaning'];
$synonym=$row['synonym'];
$antonym=$row['antonym'];
}
}
and function,
function GetWordsByID($id){
include("conn.php");
$result=$conn->prepare(" ");//Here sql statement
$result->execute();
return $result;
}
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.
I'm fairly new to php and SQL and just can't figure out the problem. Note that this is a school project, therefore the vulnerability to SQL Injections and saving the blank passwords are nothing to worry about.
After the User filled out the Login-form, he's redirected to this page:
[Some html]
<?php
if(isset($_POST['submit']))
{
ConnectSQL();
}
//Retrieve POSTed Login information
$Username = htmlspecialchars($_POST['RegUsername']);
$Email = htmlspecialchars($_POST['RegEmail']);
$Password = htmlspecialchars($_POST['RegPassword']);
function ConnectSQL() {
// SQL Server Extension Sample Code:
// (ConnectionInfo, obviously it's there in the real file)
$conn = sqlsrv_connect($serverName, $connectionInfo);
// PHP Data Objects(PDO) Sample Code:
try {
$conn = new PDO('sqlsrv:server = tcp:xxx.database.windows.net,1433; Database = userdb', 'arechon', '{NotTheRealPassword}');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully connected to SQL Server and DB";
Register();
}
catch (PDOException $e) {
print('Error connecting to SQL Server.');
die(print_r($e));
}
}
function Register($Username, $Email, $Password) {
$regquery = "INSERT INTO dbo.Users (Username, Email, Password) VALUES ('UsernameTest', 'EmailTest', 'PasswordTest')";
$conn->query($regquery);
echo '<script type="text/javascript">window.open("http://xxx.azurewebsites.net/Login.html", "_self");</script>';
The Code always seems to stop at $conn->query($regquery); and doesn't return any error messages. Sometimes it just stops, when I slightly modify the Code (e.g. replacing $conn->query($regquery); with $conn->exec($regquery); or using " instead of ') I get a HTTP500 error.
I found some similiar questions here on stackoverflow as well as on other plattforms, but none of the provided answers could solve this error. Note that I use SQL and NOT MySQL (though it wouldn't be a lot of work to change that if you think that could solve my problem).
Okay I have a bit of a question dealing with $_POST. I'm attempting to send a few values from an Android App (Using HTTPclient) I'm developing but the PHP sends the message from the exception back. I'm trying to figure out why is that happening and how to fix it:
login
<?php
//load and connect to MySQL database stuff
require("configmob.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
myusername,
mypassword
FROM Customer
WHERE
myusername = :myusername
mypassword = :mypassword";
$query_params = array(
':myusername' => $_POST['username'],
':mypassword' => $_POST['password']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
}
?>
config
<?php
// These variables define the connection information for your MySQL database
$host = "mysql17.000webhost.com";
$dbname = "a4335408_data1";
$username = "******";
$password = "******";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like ¢ or €, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an
associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
Thank you and I hope this question isn't too difficult or anyhting.
Try replacing the static error message with the exception message to see what's going wrong
Change:
$response["message"] = "Database Error1. Please Try Again!";
to:
$response["message"] = $ex->getMessage();
Conditions in a WHERE statement must be separated with AND keyword