PHP mySQL Simple Echo from SELECT - php

I am trying to create a simple echo from a SELECT from DB.
It echos blank always.
Here is the code:
<?php
$username = "xxxx";
$password = "xxxx";
$hostname = "xxxx";
$conn = mysqli_connect($hostname, $username, $password, "xxxx");
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$user = $_GET['user'];
$pass = $_GET['pass'];
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$retval = mysqli_query($conn, $sql);
echo($retval);
mysqli_close($conn);
?>
It would be greatly appreciated if someone could help and tell me what I am doing incorrectly :)

If it worked, you didn't get ID back, but a "mysqli_result" object.
Try print_r($retval) to see what you really got.
If it's a mysqli_result object, you need another step to get the data.
while ($row = $retval->fetch_assoc()) {
echo $row['id'];
}

According to the manual:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return TRUE.
Moreover, please note that a query that runs but returns zero results is still considered a "successful query" since the query did run in the database and an empty result set is a legitimate response. This means the query will still return a mysqli_result object.
As I understood the code so far, if you want to echo results returned you could use mysqli_fetch_array(), so your code would become:
/* numeric array */
$row = mysqli_fetch_array($retval, MYSQLI_NUM);
And you can echo it as:
echo $row[0];
or
/* associative array */
$row = mysqli_fetch_array($retval, MYSQLI_ASSOC);
And then you could echo as:
echo $row['id'];
Furthermore, you can use mysqli_fetch_assoc() to loop over your results or for fetching single row instance purposes, an example is:
while ($row = $result->fetch_assoc()) {
echo $row['id'];
}
Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in the resultset.
And if you want to check if your query has found any rows, you can use mysqli_num_rows
Which works as the following:
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($retval);

Do you know if you are connected to the database or not? You could try changing a value to see if the error comes up or not.
If thats not the issue this should work better:
$host = 'xxxx';
$user = 'xxxx';
$pass = 'xxxx';
$db = 'xxxx';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$whateverString = $row['cakes'];
}
echo $whateverString;
Now lets say that you had a value in the mysql row called cakes that is equals to 5 then it will fetch that specific string from the row if the user and pass is correct.
So the value above will output "5" if the mysql value 'cakes' is 5.

Thanks for your answers, people!
I ended up with this:
$q=mysqli_query($con,"SELECT id FROM `users` WHERE user='$username' and pass='$password'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if(json_encode($data)== '[]'){
echo 'error';
}else {
echo json_encode($data);
}
?>

Related

How to Remove JSON Object ID in php json encode function while using JSON_FORCE_OBJECT Param

Here is my PHP Code which fetches the data from DATABASE and shows as JSON Encode.
<?php
// Initialize variable for database credentials
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'sfm';
//Create database connection
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
//Check connection was successful
if ($dblink->connect_errno) {
printf("Failed to connect to database");
exit();
}
//Fetch 3 rows from actor table
$result = $dblink->query("SELECT quote, author FROM quote ORDER BY RAND() LIMIT 1");
//Initialize array variable
$dbdata = array();
//Fetch into associative array
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
echo json_encode($dbdata, JSON_FORCE_OBJECT);
?>
And Here is the Output I'm getting as JSON.
I Need my JSON Output Like this..
Help me.. Thanks in advance
As you are expecting just one row, you can ditch the loop and just fetch the first record, then encode just this row rather than an array of 1 row...
$row = $result->fetch_assoc();
echo json_encode($row, JSON_FORCE_OBJECT);
Not sure where the id comes from in the result, this may be just a case of adding it to the SQL select.

how to store mysql select statement inside php variable using mysqli

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 />";
}

Convert data from db to JSON using php

I have already seen many questions but nothing has helped.
I want to convert my data from database (MySQL) to JSON using PHP. This is my PHP code:
init.php
<?php
$db_name = "webappdb";
$mysql_user = "root";
$mysql_pass = "root";
$server_name = "localhost";
$charset= "utf8";
$con = mysqli_connect($charset, $server_name, $mysql_user, $mysql_pass, $db_name);
?>
listViewBooks.php
<?php
include("init.php");
header('Content-Type: application/json');
// get all items from user_info_book table
$sql = mysqli_query("SELECT * FROM `user_info_book`");
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$output[] = $row;
}
echo json_encode($output);
echo json_last_error();
mysqli_close($con);
?>
The error is 0, so it's nothing.
There are a bunch of problems in your code. For starters, you have this:
$sql = mysqli_query("SELECT * FROM `user_info_book`");
$res = mysqli_query($con,$sql);
$sql is a mysqli_result object on success or boolean false on failure. Here, it's false because you didn't pass the database link ($con). See the docs. You shouldn't, don't need to, and can't store the result of mysqli_query in a variable ($sql) and then pass that variable in another call to mysqli_query. Just do:
$sql = "SELECT * FROM `user_info_book`";
$res = mysqli_query($con, $sql);
Also, you initialize one array, then add to another:
$result = array();
while($row = mysqli_fetch_array($res)){
$output[] = $row;
}
Perhaps you mean to do $output = array();?
You would benefit from using an IDE like PHPStorm.
So you execute a query and assign the result to $sql:
$sql = mysqli_query("SELECT * FROM `user_info_book`");
But then you query again and use the $sql result as if it were a string:
$res = mysqli_query($con,$sql);
Probably more what you were thinking:
$sql = "SELECT * FROM `user_info_book`";
$res = mysqli_query($con,$sql);
You should use error reporting when developing:
error_reporting(E_ALL);
ini_set('display_errors', '1');
You code is bad:
$sql = mysqli_query("SELECT * FROM `user_info_book`");
^---missing DB handle
^---query result handle
So $sql becomes boolean false for failure, because you didn't call the query function correctly.
You then blindly use this boolean false as if it was a query string:
$res = mysqli_query($con,$sql);
^---boolean false, due to previous errors
So basically, you assumed your code was perfect, and could never ever possibly have any problems, so failed to add any error handling. Since you have no error handling, you utterly ignored the errors that DID occur.
Never EVER assume success - this code is a perfect example of WHY. Your sql is syntactically perfect, yet it failed because you didn't call the query function properly.
Always assume failure, check for failure, and treat success as a pleasant surprise.
You initialize an array called $result but try to use an array with the $output identifier which has not been initialized, PHP will not auto-initialize an array variable for you. That is where one error comes from.
The second error I noticed is:
mysqli_query("SQL")
You forgot to pass in the database connection resource as it should be:
mysqli(db_connection, sql_query)
Fix those then if you need more assistance, comment below.
Have a good day.

Connection is made to the database with php script but no values are returned

I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.

Mysql Query, comparing values and assigning to PHP variables

I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>

Categories