Use array results from database as php variables - php

The application I'm building requires some users to be linked to eachother.
There will be users and mentors. The database field "mentor_link" has a value. This value determines which users the mentor is linked to.
What I'm trying to do is search the database for the users with a certain "mentor_link" value and save their usernames as php variables to be used later.
Using json_encode() AND print_r simply displays something that looks like this:
[{"userName":"dave","0":"dave"},{"userName":"ely","0":"ely"},{"userName":"mentor1","0":"mentor1"}]
What I'm looking for is to target each username and save it as a variable. For example: $user1 = dave; $user2 = ely; etc etc.
All the other examples I've found only allow me to display it the same way as above.
My code is as follows:
$stmt = $user_home->runQuery("SELECT userName FROM tbl_users WHERE mentor_link=101");
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
The database is connected fine and I'm able to pull single values based on the users details but I can't figure out how to get info on other users and display it/save it as a variable.
Oh and I'm using PDO to connect to the database.

After this line:
$result = $stmt->fetchAll();
You can do anything with that data
print_r($result[0]);//user1
print_r($result[1]);//user2
or
$user1 = $result[0];
$user2 = $result[1];
then
echo $user1['userName'];//dave
echo $user2['userName'];//ely

Related

How do I get only one value for the data I fetched from database using fetch function

I am new to php and had chosen to stick to PDO format. I have been able to set up a workable registration and login system, but my challenge is fetching data from my database which would be used in other page of the user profile page I created. I had tried all the many examples and methods I was able to get on the internet but there are not working, or rather I don't know how to use it, where I want to insert the variable will still be empty.
The only fetch function I was able to get will select all the row, for instance, if it is email, it will fetch all the registered emails in the database which is not suppose to be. The email should only be for the user whose profile is opened.
Here are the codes. I am sure someone will help me figure this out. Thanks
$data = $pdo->query("SELECT * FROM databaseName")->fetchAll();
//this one is in the body where i want to insert the email
foreach ($data as $row) {
echo $row['email']."<br />\n";
}
I tried everything my little knowledge of php but all to no avail. If i decide to use any other one, nothing will show.
You can try other alternative to achieve the same,
$stmt = $pdo->query('SELECT * FROM databasetable');
while ($row = $stmt->fetch())
{
echo $row['email'] . "\n";
}
If you are only interested in the email from the returned results, I would look to do the following:
$stmt = $pdo->query('SELECT `email` FROM databasetable');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['email'] . "\n";
}
Or
$stmt = $pdo->query('SELECT `email` FROM databasetable');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC))
foreach($data as $row)
{
echo $row['email'] . "\n";
}
If you want to check that the data coming back is good, I would add a "print_r($data);".
You can just take the first element of the results.
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
or use fetch()
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetch(PDO::FETCH_ASSOC);
I´ve also put a LIMIT at the end of your query, so you dont fetch unneeded data.
Unless I am missing something then surely you should be specifying a where in your SQL query, why would you get the entire database and loop through it until you find the email you want?
When you redirect the logged in user you must(or if you aren't then you should) be passing something about the user, e.g setting the userid in the session. Then you can use this to create more useful profile data with a query that says select email from table where userid = :userid - then when you fetch the result you will have the data you need.
Naturally I can't write the exact query without knowing your structure but getting a whole tables worth of data every time is unscalable

Mysqli print and show in browser from table

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.

How do you fetch data using PDO?

I'm fairly new to PDO in PHP and I'm trying to make a simple log-in form. I need to be able to fetch the data and can't seem to make that work with fetchColumn(), which I need to check if the user and password match.
$query = "SELECT * FROM administrator
WHERE user = :user
AND pass = :pass";
$res = $db->prepare($query);
$params = array("user" => $username, "pass" => $password);
$res->execute($params);
$num_rows = $res->fetchColumn(1);
if ($num_rows) {
$_SESSION['user'] = $num_rows['user'];
header('Location: .');
exit();
} else {
echo "Failure";
}
if (isset($_SESSION['user'])): ?>
<p>Hello, <?= $_SESSION['user']; ?>! This is admin content.</p>
Logout
<?php endif; ?>
When using this code, using the username adminuser, the output is:
"Hello, a! This is admin content."
when it should be:
"Hello, adminuser! This is admin content."
So, how does one fetch the data when the fetchColumn() function has already been executed?
I think you are misunderstanding what fetchColumn does. It will simply return a single value.
You have two options:
Change $num_rows['user'] to just $num_rows (strange naming convention there by the way). Here I'm assuming that you are actually targeting the correct column. See note below about using *
or
Use $res->fetch(PDO::FETCH_ASSOC) instead of fetchColumn, which will return an associative array containing all values in the row (which you can then continue to access with $num_rows['user']
If you go for option 1, I strongly recommend that you define which columns should be returned in your SELECT statement. Using fetchColumn with SELECT * FROM is very fragile, because the order of columns may change if new fields are added. To be honest, it's rare that you should use * anyway, so I'd probably specify the columns in any case.

Obtain resource from POST php

Lets say I have a database full of info, and I want the user to find his info by inputting his ID. I collect the input of the user with:
'$_POST[PID]'
And want to put it into a resource variable like:
resource $result = '$_POST[PID]';
In order to print out their information like :
while($row = mysql_fetch_array($result))
{
echo all their information
echo "<br>";
}
However I cannot create the resource variable because it is telling me that it is a boolean. How can I fetch that resource in order to print the list?
Several problems with this
First, a resource is something like a database result set, a connection (like fsockopen), etc. You can't just declare or typecast a variable into a result set
Second, you need to do something like SQL to fetch the data based on that ID. That involves connecting to the DB, running your query and then doing your fetch_array
Third, mysql_ functions are depreciated. Consider using mysqli instead.
I think you're having problems displaying the result set.
Try this
$id = $_POST['PID'];
$result = "SELECT * FROM table WHERE id ='.$id.'";
while($row = mysqli_query($result))
{
echo $row[0]; //or whichever column you want to display.
//$row[0] will display your
// PK
}

PHP Using Get Post in WHERE function

On one page I have a form which POSTs the data entered in the 1 field across to another page.
On this page which you are directed to after entered data in the form field is a connection to a sql database. It happily rePOSTs the form field data on the page. Then I have got the PHP for retrieving the information from the database. This works nicely when the WHERE part is fixed manually ('criteria') however I would like the WHERE criteria for this search to be the form data from the previous page.
is there a way to echo the data to it? The form data is successfully getting to the displaying page however need help with the WHERE part.
That line of code currently is...
$result = mysqli_query($con,"SELECT * FROM table WHERE field = 'formdata'");
Any help would be appreciated greatly.
Right now, query compares field to the actual string 'formdata'. You'll want to grab the formdata, if you're POSTing, like this:
$result = mysqli_query($con, "SELECT * FROM table
WHERE field = '" . $_POST['formdata'] . "'");
Although, note that you'll need to use prepared statements to make this secure. See here and here.
I use PDO, but mysqli should be roughly the same
$formdata = $_POST['input'];
$stmt = $con->prepare('SELECT * FROM table WHERE field = ?');
$stmt->bind_param('s', $formdata);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}

Categories