PHP PDO Service No Data - php

I have the below REST web service that I am using to get user information from User table:
$name = htmlentities($_GET["name"]);
$name = strtoupper($name);
$dbh = new PDO("oci:dbname= $dbhost", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("select * from Users where username =:name");
$sth->bindParam(':name', $name);
$sth->execute();
$result = array();
$result["User"] = $sth->fetchAll((PDO::FETCH_ASSOC));
print_r ($result); //returns no data
When I print out the results, no data is returned. If I hard code a username value instead of using :name, then data comes back:
$sth = $dbh->prepare("select * from Users where username ='TESTUSER'");
I am not sure what I am doing wrong with the binding of the variable that is causing the SQL to run incorrectly. I tried using bindValue and bindParam and still returns no data. I am not recieving any errors, just no data.
UPDATE: It looks like the syntax is correct. Is there anything on the Oracle side that would prevent a prepared statement from being run?

I figured out why data wasn't returning on the query. The database has the username field set as a CHAR(8) and usernames that were being passed only had 7 characters so it was failing. I need to append a blank space at the end of the string for it to match.

Related

How to store database data into a local variable for a connection system [duplicate]

I got a numerical ID of 20 characters witch looks like 10527391670258314752, given this ID, how can I get the username associated with it?
The table looks like this:
id | name | password | balance
10527391670258314752 | Jhon | 12345 | 12.51
The username retrieved from the database should then be stored into $_SESSION['name'].
I've tried this:
$connection = mysqli_connect('localhost', 'root', '', 'user_data');
$id = '10527391670258314752';
$query = "SELECT username FROM user_data WHERE id = '$id'";
$result = mysqli_query($connection, $query);
$record = mysqli_fetch_array($id);
$_SESSION['id'] = $record;
echo $_SESSION['id'];
The output is Array() instead of the name.
That's actually a very good question that has almost no good answers on Stack Overflow.
Basically you need the following steps to perform a SELECT query using mysqli:
create a correct SQL SELECT statement and replace all variables in the query with with question marks (called placeholders or parameters)
Prepare the resulting query
Bind all variables to the previously prepared statement
Execute the statement
get the mysqli result variable from the statement.
fetch your data
The detailed explanation can be found in my article, How to run a SELECT query using Mysqli, as well a helper function to simplify the routine.
Following this plan here is your code
$sql = "SELECT * FROM users WHERE id=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $id);
$Stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch the data
now you can store the username in the session variable:
$_SESSION['name'] = $user['name'];
I would strongly recommend that you avoid the mysqli extension. You should use some database abstraction library instead of using the mysqli functions directly; the mysqli class is not suited to be used on its own.
If you really want to do it purely with the mysqli class, you have few options.
First, you need to open the connection properly. These 3 lines ensure you have the connection ready:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // enable error reporting
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset
Then you need to prepare a statement, bind the parameter and execute it.
$id = '10527391670258314752';
$stmt = $mysqli->prepare('SELECT username FROM user_data WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
Once the statement is executed you need to fetch the results. If you have only one variable you could simply use bind_result()
$stmt->bind_result($_SESSION['name']);
$stmt->fetch();
echo $_SESSION['name'];
However, this approach is not recommended and not very flexible. Instead it's better to fetch the whole result set and get an array containing the first row.
$result = $stmt->get_result();
$row = $result->fetch_array();
$_SESSION['name'] = $row['username'];
echo $_SESSION['name'];
As an alternative with PDO the same code would look like this:
session_start();
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass, [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
]);
$id = '10527391670258314752';
$stmt = $pdo->prepare('SELECT username FROM user_data WHERE id=?');
$stmt->execute([$id]);
$_SESSION['name'] = $stmt->fetchColumn();
echo $_SESSION['name'];

Prepared statement returns no results

I have been chasing my tale with this for a long time. I have not been able to find an issue with this code:
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
echo $stmt->num_rows." ".$username;`
The CUSTOMER table in my database has three columns: username, pwd, and email. But nonetheless, no results are returned when I assign the $username variable to a value I know exists in the database. I know it exists because this query
$results = $db->query("SELECT * FROM CUSTOMER WHERE username ='$username'");
echo $results->num_rows;
Displays one row, which is what is expected. Can anybody please tell me why my prepared statement will not produce the correct results? I have tried several variations of quoting, not quoting, hardcoding the variable's value, but nothing works. I am on a university server so I have no control over PHP's or MySQL's settings, but I'm not sure that has anything to do with it. It seems like a coding issue, but I can't see anything wrong with the code.
num_rows will be populated only when you execute $stmt->store_result();.
However, 99.99% of the time you do not need to check num_rows. You can simply get the result with get_result() and use it.
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
// ...
}
If you really want to get the num_rows, you can still access this property on the mysqli_result class.
$result = $stmt->get_result();
$result->num_rows;
You've executed the query successfully, but not done anything with the result. After $stmt->execute();, you're looking for $stmt->bind_result($result);.
With this, you'll have access to the user's information in the $result variable.

PDO Prepared Statements and MSSQL databases not functioning correctly

I'm having a problem running prepared queries on a MSSQL database using PDO. I can connect to the database and run SELECT queries with no parameters, but now I'm trying to run a simple SELECT query with one parameter, :user. However, the code does not return any values, despite the fact that there definitely is a database row with that value in. Here's the code I'm using:
$db = new PDO('dblib:host='.$dbHost.';dbname='.$dbName.';charset=utf8mb4',$dbUser, $dbPass);
$stmt = $db->prepare('SELECT * FROM customer WHERE email_address = :user ');
$stmt->bindValue(":user", $_SESSION["username"], PDO::PARAM_STR);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
I receive no output from the var_dump. I know that in the database there is a correct row, so I tried:
$stmt = $db->prepare("SELECT * FROM customer WHERE email_address = 'the#email.com'");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
And yet still no value was returned. Am I doing something wrong with PDO? If I type this exact query into the query bar it runs.
you forgot to execute your query.
right after the paramter binding, put this code:
$stmt->execute();
Ok, I'm an idiot. Forgot to execute the query. Amended code for people in the same predicament:
$db = new PDO('dblib:host='.$dbHost.';dbname='.$dbName.';charset=utf8mb4',$dbUser, $dbPass);
$stmt = $db->prepare('SELECT * FROM customer WHERE email_address = :user ');
$stmt->bindValue(":user", $_SESSION["username"], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);

MySQLi prepared statement silently failing second execution

I am attempting to make a simple system where, once you view forum thread it updates an existing array entry with the current UNIX time in the DB table that holds the user's account information. The column is set to accept MEDIUMTEXT and is set as NOT NULL.
However, while the first prepared statement works as intended and I receive the correct value, and the json_table is correctly re-encoded, the second query does not update the column data. No errors (no matter what error level I set mysqli to). Neither of the parameters I am binding are NULL and are correct.
I am stumped as to why this is happening. MySQLi magic that I haven't learned? Restrictions somewhere?
$DB = GetDatabaseConnection();
$Statement = $DB->prepare("SELECT `forum_newpost_icondata` FROM `user_accounts` WHERE `id` = ?");
print(mysqli_error($DB));
$Statement->bind_param("i", $UserLoggedIn['id']);
$Statement->bind_result($JSONTable);
$Statement->execute();
$PostData = json_decode($JSONTable);
$PostData[$ThreadID] = time();
$PostData = (string)json_encode($PostData);
$Statement->free_result();
$Statement->close();
$Reinsertion = $DB->prepare("UPDATE `user_accounts` SET `forum_newpost_icondata` = ? WHERE `id` = ?");
print(mysqli_error($DB));
$Reinsertion->bind_param("si", $PostData, $UserLoggedIn['id']);
$Reinsertion->execute();
print(mysqli_error($DB)); // Checking after execute is still blank
$DB->close();

What is the proper way to escape a $_SESSION username for use in a mysql query?

I am using the stored $_SESSION username:
$usernameunesc = htmlentities($_SESSION['username'], ENT_QUOTES, 'UTF-8');
and escaping the variable as follows:
$username = mysqli_real_escape_string($link, $usernameunesc);
and then using it to perform the following query:
$query = mysqli_query($link, "SELECT id FROM users WHERE username = '".$username."'");
The last query returns an output of
1111
If I remove $username from the query and change it to 'demo' (which is what the username actually is) the query returns an id of 12 successfully, but using the $username variable does not work. Am I not properly escaping the string? Is there a better way to do this? By the way, I can also perform the query in the SQL command line and it works fine, so I know the query isn't the problem.
As you are using mysqli, I suggest you use a prepared statement - it will automatically escape the variable.
if ($stmt = $mysqli->prepare("SELECT id FROM users WHERE username =?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $usernameunesc);
/* execute query */
$stmt->execute();
}
Full example right here http://php.net/manual/en/mysqli.prepare.php

Categories