Mysqli print and show in browser from table - php

My connection & sql queries have already been tested and they work. I am just trying to print one column of data into my browser for output so I can test the rest of the database. I am just trying to print one row and when I run the code, nothing shows up in the browser as output. The database column name is "type" and there is a "1" in there for the user I am logging in with. The login works but I am trying to read the integer in the database in order to direct it to a specific profile. I can't get anything to printout from my table into the browser.
$role = "SELECT type FROM fp.user WHERE usname ='$username' AND pswd = '$password'";
$access = mysqli_query($link, $role);
$row = mysqli_fetch_row($access);
echo $row['type'];

There may be a problem with your query. You should check to see if $access is first false (Which would indicate a query failure), and echo out the error associated with the query.
$role = "SELECT type FROM fp.user WHERE usname ='$username' AND pswd = '$password'";
$access = mysqli_query($link, $role);
if ( !$access )
{
echo 'There was a problem running this query: ', mysqli_error($link);
exit;
}
$row = mysqli_fetch_row($access);
Also, according to the docs:
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.
Check to make sure the user/password combo in the database is correct. Another issue could be that no user exists for that $username/$password combo.

Related

Check if value is found in SQL table within PHP script?

I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }

Not getting the expected user information

I'm trying to make an admin page and allow only users with role 2 for some reason its not giving me the information I expected.
<?php
session_start();
require_once('includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: login.php');
$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false;
if($user['role'] == '2'){
echo "Hello $user['name']";
}
else {
header('location: index.php');
}
?>
When I do vardump($user) its giving me the output 1.
When I echo the $_SESSION['id'] it is giving me the right id (the session id is the same as user id).
Right now what you have done is, you just executed the query and had the resultset stored in $user. You need to fetch the results from the Result Set.
$user = mysqli_fetch_array($user);
Now it should work as expected.
Update: You should also handle the following:
Sanitization: Make sure you use ' for the values and ` for the column names. Also use mysqli_real_escape_string() for escaping some obvious stuff.
Validation: That's the next most important. Try checking if the resultset has any rows returned. You can do by using mysqli_num_rows($user) > 0 or precisely in your case, mysqli_num_rows($user) == 1.
Variables: Here in the example, I have used the same $user for the Result Set as well as the row. It is always better to have two separate variables, say, $userRes (for result set) and $userData (for the fetched data).
Hope this should answer your question.
After a successful select query mysqli_query() will return an mysqli_result object. You have to itterate over that to get your results. For example:
$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false;
if(user ){
// Cycle through results
while ($row = user ->fetch_object()){
$users[] = $row;
}
$user->close();
}
You're not fetching the results... If you check the manual, and look for the return value of mysqli_query(), you'll find:
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
So go ahead and fetch it:
//$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false; // I'm unfamiliar with this || false stuff.
$result = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']);
$user = mysqli_fetch_array($result);
It's also a good idea to sanitize your input (in order to prevent SQL-injection) and to check whether there are any results with mysqli_num_rows().

How to retrieve data from SQL Server?

I was wondering why my query is returning null when I know there is data there.
my query is as follows:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note FROM Notes WHERE NoteID = 2";
$showNotes = sqlsrv_query($conn, $showNoteInfo);
var_dump($showNotes);
}
I have tested $_POST['noteid'] and that displays an ID no problem, in theory this id will replace where I have the number 2 in my query.
However I know in my table in the Notes table where NoteID = 2 the text should be like this
However var_dump displays "resource(7) of type (SQL Server Statement)"
And I have also tried a different method of displaying it and that returned as the query expected resource and was given NULL, so why is this query not getting any results?
My connection details are in an include at the top of the page and are like this: http://pastebin.com/qz3tScdW
If you need anything else please ask.
Underlying question, why is my Query returning NULL when I know theres data there?
You never actually try to retrieve your data. sqlsrv_query performs the database query, but it doesn't get the data. You need to use sqlsrv_fetch_array (or sqlsrv_fetch_object) for that:
$stmt = sqlsrv_query($conn, $showNoteInfo);
if (sqlsrv_has_rows($stmt)) {
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
var_dump($data['Note']);
} else {
echo "No data found";
}

mysql - strange thing with update and select statements

I have a strange mysql-thing going on here, it is about the following code:
$res = mysql_query("SELECT * FROM users WHERE group='".$group."'");
if (mysql_num_rows($res)==1) {
$row = mysql_fetch_assoc($res);
$uid = $row['uid'];
$user_update = mysql_query("UPDATE fe_users SET group = 5 WHERE group='".$group."'");
return 'ok';
} else {
return 'not ok';
}
I am checking, if there is a user with the group = $group. If so, the group is updated to 5 and after that the string "ok" is returned, if no user with group=$group exists, as you can see the string "not ok" is returned.
This should be very easy, but the problem now is, that if there is a user with group=$group, the update is done correctly, but instead of returning "ok", php returns "not ok", as if the change from the update is been taken into account for the above executed select retroactively. I dont understand this. Any help would be really appreciated.
Thanx in advance,
Jayden
I think 'group' is a reserved keyword that you have used as a field name, change it or use like
$res = mysql_query("SELECT * FROM users WHERE `group`='".$group."'");
and
$user_update = mysql_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
and you can use count($res)==1 instead of mysql_num_rows($res)==1 if it is a problem.
Reference: Mysql Reserved keywords.
I am not sure if this has any merit but try using this style in your SELECT and UPDATE commands: WHERE group='$group', without using string joins. Other than that I can't seem to see why you are getting an update and not being returned "ok".
You are checking if mysql_num_rows($res)==1, so you'll return ok if there is exactly one user on that group. If there are two or more users, it will return not ok. Probably not what you want, right? I think you should check if mysql_num_rows($res)>=1.
You might consider modifying the placement of your brackets, and changing your num_rows check, like so:
$res = mysqli_query("SELECT uid FROM users WHERE `group` ='".$group."'");
if (mysqli_num_rows($res)>0) {//there was a result
while($row = mysqli_fetch_assoc($res)){
// grab the user id from the row
$uid = $row['uid'];
// and update their record
$user_update = mysqli_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
if(mysqli_num_rows($user_update)==1){
return 'ok, updated user';
} else {
// database error
return 'not ok, unable to update user record';
}
}//end while row
}else{
return 'No results were found for this group.';
}
By selecting just the column you want, you reduce the query's overhead. By comparing the initial result to 0 instead of 1, you allow for groups with many members. By wrapping the update function in a while loop, you can loop through all the returned results, and update records for each one. By moving the test that returns 'ok'/'not ok' to check for success on the update operation, you're able to isolate database errors. The final else statement tells you if no update operation was performed because there are no members of the group.
BTW, for future-compatible code, I recommend using mysqli, as the "mysql_query" family of PHP functions are officially deprecated. See http://www.php.net/manual/en/mysqli.query.php for a quick start, it's largely the same thing.

Comprehension disconnect in MySQL

Novice Alert
A mySQL table "tokens" contains a field, "dl" (DL), which is an integer (values: 0, 1 or 2)
For the row where field "token"==$stripped_token, the current value of "dl" is 0
I wish to read the record, increment the number found in field "DL" (zero) and update the record. Here's what I'm trying:
function sql_update_token($stripped_token)
{
global $mysqli ;
$curr_dl = $mysqli->query("SELECT dl FROM tokens WHERE token = ".$stripped_token) or die (mysqli_error());
$new_num = $curr_dl + 1;
$result = $mysqli->query("UPDATE tokens SET dl=".$new_num." WHERE token = ".$stripped_token) or die (mysqli_error());
}
The value of field DL is now "2" ! Why 2?
In troubleshooting the above, I tried this:
function sql_get_dl($stripped_token)
{
global $mysqli ;
$curr_dl_num = $mysqli->query("SELECT dl FROM tokens WHERE token = ".$stripped_token) or die (mysqli_error());
return $curr_dl_num;
}
$test = sql_get_token($stripped_token);
echo('[$test] == [ '.$test.' ]<br />');
The problem is that $test does not contain the number "0", as I had hoped. Instead, it contains: "current_field", "field_count", "lengths", "num_rows" and "type" (those text strings, in an array.
What are my errors?
One problem is that msysqli->query doesn't return the value you think it returns. It returns a result object. You then need to get at the data in that result. i.e.:
global $mysqli ;
$result = $mysqli->query("SELECT dl FROM tokens WHERE token = ".$stripped_token) or die (mysqli_error());
$row = $result->fetch_row();
$curr_dl_num = $row[0];
Think of $result as a table. fetch_row() gets the first row, and $row[0] gets the first cell of that row. This is really inconvenient, since you are only getting a table with one value in it, but with other queries, where multiple results are returned, being able to step through them using fetch_row() is really useful.
As well, how are you generating your $stripped_token value, since you said that wasn't behaving as you expected? If you are reading it from a mySQL query, your problem is probably the same - it might be a result object, and not a single value as you expect.
EDIT:
Never mind the bit about $stripped_token, I misinterpreted the last part of your question.

Categories