Cannot retrieve name from Users database (mysql) using PHP - php

I'm trying to display a "Welcome back, <name>." to my blog when I log in back. I'm using php to access the database, get the name and last name of the username currently in $_SESSION['username'], and then print it back in the index.
So the function to query the database is:
function get_full_name($username){
$real = array();
$query = mysql_query("SELECT `name`, `last` FROM `users` WHERE `user` = `{$username}`");
$row = mysql_num_rows($query);
foreach($row as $k => $v)
{
$real[$k] = $v;
}
return $real;
}
Then the part of the html where it calls the function above:
<div id="menu">
<?php
$temp = $_SESSION['username'];
$real[] = get_full_name($temp);
if(isset($_SESSION['username']))
{
echo '<br />'.'Welcome back, '. $real['name'] . '.';
}
?>
</div>
The output of the above codes is:
Welcome back, .
var_dump($real) gives:
array(1) { [0]=> array(0) { } }
var_dump($real) after changing to mysql_fectch_assoc:
array(0) { }
Fixed: The error was not using the single quotes ' {$username} '
By changing them, it worked like a charm, cheers to all!

Curiously you are using mysql_num_rows to get the results of your query. This will only return the number of rows. You'll be better off using mysql_fetch_assoc to get the associative array of results.
You also need to change your backticks to single quotes around {$username} in the query.
Something like:
function get_full_name($username){
$real = array();
$query = mysql_query("SELECT `name`, `last` FROM `users` WHERE `user` = '{$username}'");
$row = mysql_fetch_assoc($query);
foreach($row as $k => $v)
{
$real[$k] = $v;
}
return $real;
}

Your get_full_name() function should be like this:
function get_full_name($username) {
$real = array();
$query = mysql_query("SELECT `name`, `last`
FROM `users`
WHERE `user` = '{$username}'");
if (mysql_num_rows($query)) {
$real = mysql_fetch_assoc($query);
}
return $real;
}
Notes:
Use single quotes for the variable: '{$username}' instead of `{$username}`
Use mysql_num_rows() for checking if the result is not empty.
Use mysql_fetch_assoc() for retrieving the row.
Calling the function:
$temp = $_SESSION['username'];
$real = get_full_name($temp);
if (isset($temp) && count($real)) {
echo '<br />Welcome back, '. $real['name'] . '.';
}
Notes:
Use $real instead of $real[].
Check if $real empty with count().

Change this line $row = mysql_fetch_array($query);

Two issues I see.
1) You are using mysql_num_rows, not fetching the array of data from the database.
function get_full_name($username){
$real = array();
$query = mysql_query("SELECT `name`, `last` FROM `users` WHERE `user` = `{$username}`");
$row = mysql_fetch_assoc($query);
foreach($row as $k => $v)
{
$real[$k] = $v;
}
return $real;
}
2) Looks like $real is a multi-dimention array in your code. Try this instead:
<div id="menu">
<?php
$temp = $_SESSION['username'];
$real = get_full_name($temp);
if(isset($_SESSION['username']))
{
echo '<br />'.'Welcome back, '. $real['name'] . '.';
}
?>
</div>
Notice I've removed the [] at the end of $real.

Use mysql_query() to get the result of running the query, then use mysql_fetch_assoc() to get individual rows.
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
var_dump($row);
}
Note that mysql_num_rows($result) will return the number of rows in a given result.

Related

add mysql query values to an php array

I am trying to add all the query values to an array.
here is my code:
$value = $_POST['hospitalname'];
$from = $_POST['from'];
$to = $_POST['to'];
if($_POST["Submit"]=="Submit") {
for ($i=0; $i<sizeof($value); $i++) {
$sql = "SELECT sl_id from mfb_servicelog where h_id LIKE ('".$value[$i]."')";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$slid = $row["sl_id"];
for ($x=0; $x<sizeof($slid);$x++) {
echo $slid[$x];
}
}
}
}
If I print the result of $slid, it gives me this
1333853863873885215251126112711281129113023392488248924902491249224932494249524962497
These all are sl_id, and result of the query $sql. This is fine.
Now I want to put all these value into an array so that I can call this from a query like I am calling the $value in the above $sql query.
But my echo $slid($x) gives me this output, whic is the first digit of each value.
13333551111122222222222
Please suggest me the right way to do this.
Just store them in an array instead of a normal variable. Try with -
$slid[] = $row["sl_id"];
Update
if (!in_array($row["sl_id"], $slid)) {
$slid[] = $row["sl_id"];
}
And define $slid before the loop starts - $slid = array();
Or you can use array_unique()
For your code it should be -
$slid = array();
while ($row = mysql_fetch_assoc($result)) {
if (!in_array($row["sl_id"], $slid)) {
$slid[] = $row["sl_id"];
}
}
foreach($slid as $id) {
echo $id."<br>";
}

Getting PHP and MySQL to read url

So I want to be able to use a WHERE command in SQL to select certain values from a table. This is my current code however it doesn't work
$MobileNumber = $_GET["MobileNumber"];
$TeamGroup = $_GET["TeamGroup"];
if($_REQUEST=['MobileNumber']) {
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = $MobileNumber";
} elseif($_REQUEST=['TeamGroup']) {
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = $TeamGroup";
} else {
$Item = "SELECT a,b,c,d FROM Item";
};
$result = mysql_query($Item) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $value) {
print "<td>$value</td>";
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table>';
} else {
echo "No Items Assigned";
};
It works for when the url is test.php?MobileNumber=... but not when its has TeamGroup or nothing in the url. The url I have is like this: test.php?TeamGroup=11
EDIT: Added more code to let you see what I am trying to display
if($_REQUEST=['MobileNumber']){ its a wrong syntax
Try this
add this line in your url ?MobileNumber=Put your mobile num here. Thanks
than for Team group again this ?TeamGroup=put team group here.
if($_GET['MobileNumber']==TRUE){
$MobileNumber=$_GET['MobileNumber'];
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = $MobileNumber";
}
elseif($_GET['TeamGroup']==TRUE){
$TeamGroup=$_GET['TeamGroup'];
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = $TeamGroup";
}
else{
$Item = "SELECT a,b,c,d FROM Item";
}
This statement:
if($_REQUEST=['MobileNumber'])
will always be true, because you're assigning the ['MobileNumber'] array to the $_REQUEST global.
If you're trying to check whether the values are set in the $_REQUEST global, do the following:
if( isset($_REQUEST['MobileNumber']))
If you want to compare something using if condition then it must be like this
if(something == true){
// then do something
}
else{
//do something
}
Check the manual for more
What you are trying to do is not a valid one in php.You need to change this
if($_REQUEST=['MobileNumber']){
I think you can try like this
if(isset($_GET['MobileNumber']) && trim($_GET['MobileNumber'])){
And
elseif(isset($_GET['TeamGroup']) && trim($_GET['TeamGroup'])){
this should work...
if(isset($_GET['MobileNumber'])) //can also use if(isset($_GET['MobileNumber']) && !empty($_GET['MobileNumber']))
{
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = ".$MobileNumber;
}
elseif(isset($_GET['TeamGroup']))
{
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = ".$TeamGroup";
}
else{
$Item = "SELECT a,b,c,d FROM Item";
}
You could try this:
$MobileNumber = $_GET["MobileNumber"];
$TeamGroup = $_GET["TeamGroup"];
if(isset($_GET["MobileNumber"])) {
//If you enclose fields/table in `` and values in '' you won't run into quoting issues
//It's OK to not quote numbers, but you can quote them to stay standard
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item` WHERE `MobileNumber` = '$MobileNumber'";
};
if(isset($_GET["TeamGroup"])) {
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item` WHERE `TeamGroup` = '$TeamGroup'";
};
if(!isset($_GET["MobileNumber"]) && !isset($_GET["TeamGroup"])) {
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item`";
};
//Switch to mysqli_*
$result = mysqli_query($dbLink, $Item) or die ("Error in query: $Item. " . mysqli_error());
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
print '<table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
};
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $value) {
print "<td>$value</td>";
};
print '</tr>';
$row = mysqli_fetch_assoc($result);
};
print '</table>';
} else {
echo "No Items Assigned";
};
That
moves from mysql_* to mysqli_* (check my syntax - most of the mysqli_* functions are the same but there are a few differences)
uses isset & !isset to determine which query to use
encloses your query string in ticks and quotes to help make sure you don't forget to quote something properly
fixes your or die catch (you were referencing $query which didn't seem to exist)

Insert sql query result to a new query

So the task is:
Do a query like Select * from table.
Take some cell value
Insert this value to a new query.
What do I have so far:
$Conn = odbc_connect("...");
$Result = odbc_exec("Select ...");
while($r = odbc_fetch_array($Result))
// showing result in a table
Here it looks like I should use the r array and insert data like
$var = r['some_field'];
$query = 'Select * from table where some_field = {$var}";
But how can I fill this array with values and how to make it available out of while loop?
Here I'm using odbc, but it doesn't matter, I need the algorithm. Thanks.
The whole code looks like:
<?php
$data = array();
$state = 'false';
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
$data = array();
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
$state = 'true';
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//I need to use $data HERE. Doesn't work
// $state = 'false' here...
}
?>
Define array outside while loop
$data = array();//defining
while($r = odbc_fetch_array($Result))
use array_push() inside while loop
array_push($data, $r['some_field']);
then try to print array of complete data outside loop
print_r($data);
Updates
Place $data = array(); at the top of first IF statement. Try this code:
$data = array();//at top
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//print_r($data) works here also
}
try something like this to store data in array
$allrows = array();
while($r = odbc_fetch_array( $result )){
$allrows[] = $r;
}
use foreach loop to print or use as per your choice
foreach($allrows as $singlerow) {
//use it as you want, for insert/update or print all key value like this
foreach($singlerow as $key => $value) {
//echo $key . '=='. $value;
}
}
You can try this as i understand your query hope this is your answer
$arr ='';
while($row = odbc_fetch_array($Result)) {
$arr .= '\''.$row['some_field'].'\',';
}
$arr = trim($arr, ",");
$query = "SELECT * from table where some_field IN ($arr)";
Your all task can be completed in single query
INSERT INTO table2 (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM table1

How to 'append' function variables using the URL and a question about Array's

The first question is how to run a function using the URL, I have the following function:
function do_curl($start_index,$stop_index){
// Do query here to get all pages with ids between start index and stop index
$query = "SELECT * FROM xxx WHERE xxx >= $start_index and xxx <= $stop_index";
Now when I'm trying to do curl.php?start_index=0&stop_index=2 this is not working but when i delete the function and WHERE idnum = 1 it is working.
Now the second question is how 'compile' all the fields from the rows to arrays? I have the current code:
$query = "SELECT * FROM fanpages";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query = '\'http://graph.facebook.com/'.$row['page_id'].'\', ';
echo $fanpages_query;
}
$fanpages = array($fanpages_query);
$fanpages_count = count($fanpages);
echo $fanpages_count;
echo $fanpages_query; returning
'http://graph.facebook.com/AAAAAA', 'http://graph.facebook.com/BBBBBBB', 'http://graph.facebook.com/CCCCCCCC',
(I don't have an idea how to do it in a different way, also when im doing it in such a way i can't delete the final comma which will return PHP-error.)
echo $fanpages_count; returns 1 and like you can see i have 3 there.
Thanks in advance guys!
Do a function call to do the query
function do_curl($start_index, $stop_index){
...
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
For your second question, you can use arrays and the implode function to insert commas:
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
Then use implode to print them out:
echo implode(',', $fanpages);
The whole code:
function do_curl($start_index = 0, $stop_index = null) {
$queryIfThereIsNoStartIndex = '';
$queryIFThereIsNoStopIndex = '';
$queryIfBothStartAndStopIndexAreMissing = '';
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);
echo implode(',', $fanpages);
And you should totally use mysql_escape_string for escaping the values you add to the query.

PHP: Making this grabbing from db easier/simpler way?

Is there any method i could do this easier:
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
as i only need to grab the full_name, then i make a var for the fetch_array and so, is there any way to make this simpler and echo? There was something about list(), but im not sure..
Ignoring possible security breaches and the usefulness of a DAL (see #deceze's answer), I recommend the use of mysql_result() instead of mysql_fetch_assoc() (or *_array() or whatever):
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$fullName = mysql_result($query, 0);
echo $fullName . " ";
Not easier per se but should be more in line with the intention of the query (fetch one field in one row).
The only way to abstract this any more and thereby make the actual call shorter is by using a DAL and/or ORM like Doctrine or Propel, which you should anyway.
May be not easier, but more securely:
$id = mysql_real_escape_string($show['uID']);
$query = mysql_query("SELECT `full_name` FROM `users` WHERE id = '".$id."'");
$row = mysql_fetch_array($query);
echo $row['full_name'];
Oh you can to make id with intval:
$id = intval($id);
This could make further DB-questions easier;
function mysql_fetch_scalar($res)
{
$arr = mysql_fetch_array($res);
return $arr[0];
}
$query = mysql_query("SELECT full_name FROM users WHERE id = '".intval($show[uID])."'");
$fullname = mysql_fetch_scalar($query);
echo $fullname . " ";
Sure.
Moreover, you should - to make a function out of these repetitive API functions calls.
Something as simple, as this
function dbgetvar($query){
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
have this function in your config file and use every time you want a value from database:
echo dbgetval("SELECT full_name FROM users WHERE id = '$show[uID]'");
(I hope you have $show[uID] escaped)
Of course there can be also 2 similar functions, to return a row or a rowset. Or just one but with additional parameter. Or you can combine them into class...
You can make it even escape variables for you:
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
echo dbgetvar("SELECT full_name FROM users WHERE id = %s",$show['uID']);
That's what you have to do. You could wrap that in a helper function if you're using it a fair bit, but then you'd probably want to cache the answer you get - I don't suppose the name changes all that often...
function echoName($user_id) {
$id = mysql_real_escape_string($user_id);
$query = mysql_query("SELECT full_name FROM users WHERE id = '$id'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
}
// ...
echoName($show['uID']);

Categories