Hi I am trying to get data from the database where the user can click on a person name and be redirected to some other page to see the person detail example like "user id = 1". Any idea on how to do it? If possible could you show me some example on how to do it thanks
Below is a screenshot on what I have done so far, the name below are in href so that it can redirect the user to another page and see the person details
you can use Laravel Eloquent for this one.
User::find($userid);
or using Laravel Query Builder
$users = DB::table('users')where('id','=', $userid)->get();
You can write a function for redirect in javascript with parameter is User ID. After that use your routes to get parameter (user id) on your link and write a query mysql in your controller to get data of this user id. Finally , you bring all of data from this user to your view.
function Redirect(userid) {
window.location = 'http://yourdomain.com/profile/'+userid;
}
in your view add event onclick to username.
bob
in routes/web.php add new route:
Route::get('/{userid}','Controller#index');
in your controller:
$UserID=$request->input('userid');
now your parameter on your link will stored in $UserID. You can use this value to query data and show it on you view.
Here's a sample code of how to get the desired user from the data base.
$dbUser="root";
$dbPassword="root";
$dbServer="localhost:8889";
$dbName="test_database";
$connection = new mysqli($dbServer, $dbUser, $dbPassword, $dbName);
if($connection->connect_errno)
{
exit("Database Connection Failed. Reason: ".$connection->connect_error);
}else{
echo "Connection successful..;
}
$query = "SELECT id,first_name,last_name FROM Author where user_id= XXXX ";
$resultObj = $connection->query($query);
if ($resultObj->num_rows > 0)
{
while ($singleRowFromQuery = $resultObj->fetch_array())
{
print_r($singleRowFromQuery);
echo "Author: ".$singleRowFromQuery['first_name'].PHP_EOL."<br>";
}
}
$resultObj->close();
$connection->close();
Make sure you replace the user_id appropriately and provide appropriate declaration.
you also pass data through the call url in the anchor tag using .. url ..?user_id=XXX
Related
I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .
On my website I'm listing data from the database with the use of $query->fetch(PDO::FETCH_ASSOC);. Everything is working fine except that after changing the database and redirecting with header() the user must refresh the page again to actually see the changes. I don't know what is causing this and it seems odd that the content is there but only upon a second refresh. Any help would be great. Thanks.
This is the code that is listing data back to the user.
public function getCoilInfo ($coil_id) {
//Database Connection
$db = Database::getInstance();
//Query to select all information from `coils` tables based off $coil_id
$query = $db->getConnection()->prepare("SELECT * FROM `coils` WHERE coil_id = :coil_id");
$query->execute(array(
':coil_id' => $coil_id
));
//Return array with results
return $query->fetch(PDO::FETCH_ASSOC);
}
I then reference the following class like this:
$coil = new Coil();
$coilInfo = $coil->getCoilInfo($_GET['coil_id']);
echo $coilInfo['coil_name'];
I'm new to PHP and am trying to build my a website to display information on TV shows stored in a MySQL DB. I've currently got a webpage that will create a table to display the information in the DB, however I'd like each row to link to a dynamically populated page with more info on each show (also pulling from the DB). My question is how do I get the site to know which link has been clicked and then save that as a variable so it can then be recalled on a new to populate the correct information?
I'm currently using this to populate the page.
<!--Populate page with data from SQL-->
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "media_server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th></th><th></th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>
<img src='../images/thumbnails/tv/".$row["thumbnail_path"]."'>
</td>
<td class='td_title'>
<a href='#' onclick='show_var_set();'>".$row["show_title"]."</a>
</td>
<td class='td_desc'>".$row["show_desc"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "Error - 0 results were returned my the database. Please try again.";
}
$conn->close();
?>
One option is to change your href links to point to this page and pass a GET variable you can retreive. The added bonus to this approach is you could bookmark a particular show and come back to that page, since the bookmark will include that GET variable.
So you could change your links to something like this:
echo '', $row['show_title'],'';
Then you'd retrieve that variable by testing for, then reading the GET variable and performing a db query to populate the page with that show's data.
Here's how you'd test for and retreive that variable:
if (isset($_GET['show']))
{
$show = $_GET['show'];
// Perform database lookup using $show
}
Remember to never put user input directly into a query, but use prepared statements and bind the user data to avoid the risk of SQL injection.
There are many ways to pass values from page to page but one is to use session variables:
//Include this at the top of your php scripts that use session variables
session_start();
$_SESSION['your_variable_name_here'] = value_you_want_to_store;
Then on the page you would like to access this use:
$someVariable = $_SESSION['your_variable_name_here'];
Change the SQL to return the show_id,
$sql = "SELECT show_id, show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
and use that as a parameter to the show_var_set() function.
<a href='#' onclick='show_var_set(".$row["show_id"].");'>".$row["show_title"]."</a>
The show_var_set() function can then use that parameter to get the details for that show from the database.
I'm trying to implement an ACL in my database. I have a database which looks like:
SYS_USERS { id, name, .. }
AUTH { au_id, au_name, .. }
USER_GROUPS { sys_users_id, auth_id } // bridge table
And say AUTH data looks like:
au_id au_name ...
1 admin ...
2 staff ...
... ... ...
My question is, how can I structure my query from php such that upon login, depending on your authentication level, you are presented different pages?
At the moment I have this, which seems a little off:
<?php
// code which verifies session variables etc here
$mysql_hostname = 'localhost';
$mysql_username = '...';
$mysql_password = '...';
$mysql_dbname = '...';
try {
/* Set up new DB object */
$db = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/* authenticate user access level */
// username = 'blah' for question clarity
$query = $db->prepare('SELECT au_name FROM auth WHERE au_id = (SELECT auth_id FROM user_groups WHERE sys_users_id = (SELECT id FROM sys_users WHERE username="blah"))');
// do something with results..
} catch(Exception $exception) {
$message = 'We are unable to process your request. Please try again later';
}
?>
So I guess my questions are:
Is the SELECT query adequate? Or should I use an INNER JOIN to achieve the same results? (Does it matter?)
Upon success of the query, how do I show the page depending on the level? For example, if it returned admin do I write a function such that
if ($result == 'admin') {
// show admin.php
} elseif ($result == 'staff') {
// show staff.php
} else { ... }
But this seems rather 'hard coded', i.e. if we were to extend the system for more AUTH roles, we would need to then add in more IF/ELSEIF statements to the above.
Anyone able to lead me in the right direction?
Thanks.
EDIT
So I was thinking of a new way to do this. I could add two more database tables:
PAGES { id, page_name .. }
AUTH_PAGES { au_id, pages_id, .. } // bridge between auth and pages
Which then in pages I could store page_name which would hold the authentication level required to view that page?
For example: a page called admin_page.php could only be accessed by administrators. Therefore this row in pages looks like:
id page_name
1 admin_page.php
2 members_page.php
and auth_pages:
au_id pages_id
1 1
1 2
Which is to say the auth row admin (au_name) has access to admin_page.php and members_page.php. Then all I would need to do in my PHP would be to cross reference the page name with the id from pages table with auth_pages table using echo basename($_SERVER['PHP_SELF']);.
Does that make any practical sense?
Since you mentioned its going to be simple so this is what I can suggest you.
At the time of login get the user id and then run a query with the id user as
select
a.au_name,a.au_id
from USER_GROUPS ag
inner join SYS_USERS su on su.id = ag.sys_users_id
inner join AUTH a on a.au_id = ag.auth_id
where ag.sys_users_id = {id of the user retrieved after the login validation}
Now Execute the above query and get the au_name and store it in a session variable as
$_SESSION['au_name'] = {auth name from the above query} ;
Create a function as below and execute it after the login.
get_page_access($au_id){
run a query to get all the pages for the auth id you got from previous query
store them in an array and finally to a session variable as
$_SESSION['page_access'] = $array ;
$array will hold all the pages you retrive
}
Now do the redirect based on the $_SESSION['au_name'] firstime after the login.
Now what if user hotlink an URL i.e. a non-admin user try to access a page. So for that create a file called check_access.php and add include it to all the pages other than the login page.
In this page you get the URL using PHP and get the filename from the URL, then check if that filename exists on the array $_SESSION['page_access'] and if yes user is allowed to view the page else show message.
Make sure you do session_start() before the include .
This will be fairly simple in nature
EDIT
Thanks for the help so far. I have edited my post to reflect the changes suggested below. I am using PDO for my database connection. The code I have now is as follows:
HTML
<a href="includes/delete-customer.php?userID='.$row->customer_id.'">
PHP
<?php
//MySQL Database Connect
include 'includes/config.php';
// confirm that the 'id' variable has been set
if (isset($_GET['userID']) && is_numeric($_GET['userID']))
{
// get the 'id' variable from the URL
$id = $_GET['userID'];
/* Delete row from the customer table */
$id = $dbh->exec("DELETE FROM customer WHERE customer_id = '$id'");
$stmt->execute();
}
?>
config.php
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'user';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=testDB", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I'm pretty sure the HTML is correct now and the issue lies with the delete-customer.php file. I am currently receiving the following error: Fatal error: Call to a member function exec() on a non-object
I'm not sure of how to implement the PDO query correctly. Any further advice is much appreciated.
Your HTML section says:
<a href="includes/delete-customer.php?customer_id=$id['.$row->customer_id.']">
Is this your exact HTML syntax? This argument should be the actual numerical id, i.e. --
<a href="includes/delete-customer.php?customer_id=3">
-- either by echoing $row->customer_id (assuming it exists), or some other method of knowing that user id.
Your HTML only needs to send the actual data, not any sort of variable syntax. Your receiving PHP ($_GET['customer_id']) will interpret that for you and properly pass that to MySQL.
Your URL passes userID as the get parameter, yet in your php script you're trying to access customer_id. Try changing your code to retrieve userID and it should work
if (isset($_GET['userID']) && is_numeric($_GET['userID']))
<a href="includes/delete-customer.php?customer_id=<?php echo $id[$row->customer_id]; ?>">
assuming $id[$row->customer_id] is valid.
Plus, you really shouldn't delete from database on get var unless you're doing some admin validation / access rules and guarantee you don't have anyone on the job who will go rogue and manually type in numbers there.. That's just plain crazy.