how to store mysql select statement inside php variable using mysqli - php

I know this has been asked before but I cant seem to fix my code.
What I need is to run some php code to query mysql using mysqli for a select statement to retrieve my bcrypt hashed pass so I can compare the user input with the user hashed password. NOTE: I have not yet added mysql_real_escape_string to my $POST variables.
I've changed this code a thousand times still cant get it.
Ive even copy and pasted to a new file a simple query script using num_row
and printf($row['pass']); used echo etc..... I've used fetch array ive tried almost everything I've been all via php mysql at php.net w3c.com etc etc is my system broke? Does mysqli have a bug ? and no i dont want to switch to PDO I wont stop til this is fixed and when there is no longer sql injection vulns
Heres my code:
<?php
$conn = new mysqli('localhost', 'root', '', 'social');
if (mysqli_connect_errno())
{
exit("connection failed" . mysqli_connect_error());
}
else
{
echo "connection established";
}
$db=mysqli_select_db( $conn,'social');
if ($_POST && isset($_POST['submit'], $_POST['password'], $_POST['email']))
{
$pass = ($_POST["password"]);
$email =($_POST["email"]);
$bcrypt = password_hash($pass, PASSWORD_BCRYPT, array('cost' => 12));
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
echo $fetcher;
if ($conn->query($fetcher) === TRUE)
{
echo "query has gone through now we need to store the hash<br /> for comparison";
}
else
{
echo "error did not retrieve hash info";
}

$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
Before you can fetch records from the result of the query, you need to actually perform the query. Your code should be
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$result = $conn->query($query); // This is where the query is executed
$fetcher = $result->fetch_assoc();
Two more points.
First, you don't need to call mysqli_select_db; you've already selected the database in your constructor call, so you only need to call mysqli_select_db if you want to access a different database.
Second, instead of calling mysql_real_escape_string you should look into using prepared statements, which do the same thing and also correctly handle type-matching and quoting.

Try fetching the value from database after executing the query
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$executedQuery = $conn->query($query);
if($executedQuery) {
$fetcher = mysqli_fetch_assoc($executedQuery);
echo "query has gone through ---------";
} else {
echo "error did not retrieve hash info";
}

$query = "SELECT pass FROM social WHERE id = 11"; // took the (``) out of the query and added this im assuming the value is stored in the $row variable and I may be able to use $row with the user input to verify hash via bcrypt!!!
$result = $conn->query($query);
while($row = mysqli_fetch_array($result))
{
echo $row['pass'];
echo "<br />";
}

Related

MySQL Row Isn't Found But It's There

I'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.
$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?
This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.
<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];
$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");
if(mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
$mysqli->close();
?>
It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.
Connecting to a database using the MySQLi API requires 4 parameters:
http://php.net/manual/en/function.mysqli-connect.php
If your password isn't required, you still need an (empty) parameter for it.
I.e.: $mysqli = new mysqli("host","user", "", "db");
Plus, as noted.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Footnotes:
As stated in the original post. Strings require to be quoted in values.
You need to add quotes to the strings in your query:
$query = "SELECT *
FROM characters
WHERE username='".$username."' and charactername='".$characterName."'";

Issues with PHP while statement

I'm attempting to run a while statement that will set a column in a mysql database, based on a uniqueID.
I've done this many times, and I'm not sure what I am doing wrong this time.
Basically, it works properly until I actually tell it to save the table. Here is my code
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`='$Unique'";
//mysqli_query($con, $sql);
}
}
And this works for echoing the UniqueID, and it echos the correct one. The problem comes in when I uncomment the mysqli_query($con, $sql);
in which case, nothing inside the loop is echo'd, but it DOES save the database.
For example:
Lets say this while statement loops through and finds 3 iterations of rows that have notified equal to 0 (UniqueID's 29, 26, 25), while the mysqli_query is commented, it will display these numbers on the page just fine. But as soon as I uncomment it, the database will save but it does not display any of the rest of the while loop on the page.
I need this desperately, because I plan to send a desktop notification at the same time the loop is played.
FOLLOW UP:
It also does not display the echo "test<br><br>"; on the page when the query is uncommented either.
Another follow up:
The query is saving all the data like its meant to. The problem is nothing else inside the tcheckNotifs IF statement are showing (echo's and such), like they aren't being executed. Almost like the end of the while statement is executing before anything else, including the "test" echo before the while statement.
Could anyone help me figure out why this isn't working as expected?
Here is all of my current code, with some suggestions from you guys added in, but still not working properly.
The while statement will save the query, but no other output is shown on the page.
$configs = include("config.php");
$con = mysqli_connect($configs['SQL-Host'], $configs['SQL-User'], $configs['SQL-Pass'], $configs['SQL-Database']) or die("Error " . mysqli_error($con));
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
flush(); ob_flush();
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
echo "test<br><br>";
}
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
FINAL UPDATE
With the help of Alex Andrei as well, we moved to PDO
$dsn = 'mysql:dbname=domains;host=localhost';
$user = 'root';
$password = '';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
SECOND UPDATE
Try putting your query in a variable and run the loop like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
$update = mysqli_query($con, $sql);
}
UPDATE
There is a chance the query runs first like you said. Maybe you can create an independent function to run the query and call the function from inside the while loop.
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
And your loop would look like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
ORIGINAL ANSWER
I would modify your query like this...
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
You do not need all the back ticks nor single quotes here. Might be causing an issue.
Also, I assume 1 is an integer so no need to quote that.
The Fix: PDO OF COURSE!
$configs = include("config.php");
$dsn = 'mysql:dbname='.$configs['SQL-Database'].';host='.$configs['SQL-Host'].'';
$user = $configs['SQL-User'];
$password = $configs['SQL-Pass'];
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
$sql = "UPDATE tickets SET notified='1' WHERE UniqueID='$Unique'";
The error I think it's here. You can't use $Unique between single quotes (although you already are between double quotes).
Try to fixing this replacing the line with:
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`=$Unique";
Firstly in your query you are passing a string in: ...WHERE "UniqueID"="$Unique" because of the quotes around your php variable. So your query looks like this: WHERE UniqueID = "10". Not a big deal but generally if your looking up a number your should drop the quotes.
And i suspect something is causing your query in the loop to fail, so add something to check for errors:
if(!$queryResult){
echo $con->error;
}
Run the loop and see if something is causing errors in your query. But really you should get rid of most of the backticks you have in your queries.

PHP MySQL unable to jump to row 0

I recently started studying webdevelopment and for the first project we have to make a very simple login and registration function. now I got somewhere but suddenly I started getting this error.
Unable to jump to row 0 on MySQL result index 4.
This is the code where I get the error.
$conn = mysql_connect($servername, $username, $password, $database) or die("!Server");
if(!$conn){
die("Connection error: " . mysql_error());
}else{
echo "connection made";
}
$select_db= mysql_select_db($database, $conn);
if(!$select_db){
die("Database selection failed:: " . mysql_error());
}else{
echo "database selected";
}
$login_user = $_GET['username'];
$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";
$result = mysql_query($select_password);
if(!$result){
die("Could not fetch the data " . mysql_error());
}
$password = mysql_result($result, 0);
echo $password;
I know there are other posts asking the same question but none of them where really helpful.
hope someone is able to help me.
Thanks for reading :)
It is possible that this row:
password = mysql_result($result, 0);
Cannot get rows when it does not match anything which is why you get the error.
Try instead:
if( $password = mysql_fetch_assoc($result) ) {
echo $password['password'];
} else {
echo 'no match';
}
See if that helps.
However, you really should move from mysql_* to PDO or mysqli.
I suggest to work with PDO, instead of mysql_... functions.
Not only because it's newer and object oriented but also because mysql... is deprecated.
So my answer is with PDO
From your code example I assume you have variables of servername, database, username & password. So to connect with PDO will look like this:
$con = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
Then you can take your $_GET parameter using filter_input, which is also more suggested. Simple assignment look like this:
$login_user = filter_input(INPUT_GET,'username');
and then to run & fetch query like this:
$result_query = $con->query("SELECT `password` FROM `members` WHERE `username` = '$login_user'");
$result = $result_query->fetch(PDO::FETCH_ASSOC);
Now $result is an associative array, so to get password just use:
echo $result['password'];
Thanks alot for the help :) out of these answers I got everything I needed and now I am also going to switch to PDO for the final release though I am gonna stay with MySQL for now since I have to turn it in by monday.
Thanks alot :)
Change this:
$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";
Into this:
$select_password = "SELECT password FROM members WHERE username = '$login_user'";

Cant access data in database, mysqli functions do not work but show no error

-I want to get the Id of user so I can show a welcome message in his profile but I cant seem to return the id. Maybe it is a problem in the query but when I run the code it only shows: "Error:" so I cant seem to find what is wrong.
-I have tried different sintaxes for the queries and they also work when testing them in phpmyadmin with concrete values.
-"Emri" is firstname in my language.
My db connection:
$dbc = mysqli_connect('127.0.0.1', 'root', '', 'oms_db');
my fuctions in a file fuctions.php:
ini_set ("display_errors", "1");
error_reporting(E_ALL);
include('dbc.php');
function getId($dbc, $username)
{
$query = "SELECT id FROM user WHERE username='.$username.'";
$q = mysqli_query($dbc, $query);
if($r = mysqli_fetch_assoc($q)){
return $r[id];
}
else {
echo "Error: ".mysqli_error($dbc);
}
}
function getData($dbc, $id, $data)
{
$q = "SELECT * FROM user WHERE id='.$id.'";
$r = mysqli_query($dbc, $q);
$array = mysqli_fetch_assoc($r);
echo $array[$data];
}
How I called the fuctions:
if(isset($_SESSION['username'])) {
if(!isset($_GET['id'])){
$userId = getId($dbc, $_SESSION['username']);
}
echo "Welcome to profile, ".getData($dbc, $userId, 'emri');
I have read 10 or more posts in stakoverflow but haven't found a solution. I think it is a problem with phpmyadmin or maybe queries dont work within a function.
The problem here is with the quotes and concatenates in
WHERE username='.$username.'";
either remove the dots
WHERE username='$username'";
or add double quotes
WHERE username='".$username."'";
since we are dealing with strings
https://dev.mysql.com/doc/refman/5.5/en/string-literals.html
Look into using prepared statements also:
https://en.wikipedia.org/wiki/Prepared_statement

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

Categories