Website not updating content on first refresh - php

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'];

Related

Allow only certain users to access the web page using php and sql server

I am working on a php based web app for a university. As the university has its own login system,
I would still like to restrict the web page to only certain users who are in my database.
My ms sql database looks like this:
Id UserId
1 ma580
2 am555
I have added university's login page to my web app and it works perfectly fine. But it can be used by any
user that has university's id and password.
I want to restrict it to only those users who I put in my database.
I tried something like this:
queries.php
Class Queries{
public static function getUser($ID){
$conn = DB::databaseConnection();
$sql = "SELECT User FROM Admins WHERE ID = :Id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':ID', $ID);
if ($stmt->execute()) {
return $stmt->fetch(PDO::FETCH_ASSOC);
} else {
return null;
}
}
header.php
require_once './functions/queries.php';
$ID = filter_input(INPUT_GET, "id");
$User = Queries::getUser($ID);
session_start();
if($_SESSION('User')!== $User){
header('Location: index.php');
}
This code doesn't work. When I try to login with a different Id (which is not present in the database) the page goes blank. I am new to php, any help with this one would be appreciated. Thank You

Getting data from database based on user id

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

Accessing a sql database with two different functions

I'm making a movie rating website for a project and how to do the rating system has left me at a blank. Please let me know of a proper way to this if you know.
This gets the movie number from the url and displays the relevant information in the page
<body>
<?php
global $conn;
$conn = mysqli_connect('localhost','root','','filmsdb');
function show()
{
global $film;
global $conn;
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
?>
//displays the movie information and uses radio buttons to get user rating
Then this lets the user rate the movie
<?php
}
function act1()
{
if(isset($_POST['rsub']))
{
global $film;
global $conn;
$rate = $_POST['rate'];
$sqlr= "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn,$sqlr);
}
if($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored ';
echo mysqli_error($conn);
}
}
$conn = null;
?>
</body>
</html>
when only the first function is being used, it works, but when I try to use the rating system, this error comes in the browser, mysqli_query() expects parameter 1 to be mysqli, null given... Any idea on a workaround for this?
Your issue is that the two variables you're relying on with the DB connection, $conn and $film, do not exist when the page has posted back the user rating data.
Your application's lifecycle goes like this:
1) User makes initial request. PHP starts and runs the first code block, it echoes some values to the page, page is returned to the user. Once the page is returned, the request is complete and PHP stops executing. All variables declared and in memory are lost because the process has stopped running.
2) The page returned from the PHP script arrives in the user's browser. User enters their rating and posts the data back to the server. This constitutes an entirely new request.
3) The new request arrives at the server. PHP starts up again. The web is inherently stateless, so by default it remembers nothing of the previous request. Certainly not the names or values in any in-memory variables - the process that contained them died long ago and has no association with the new one.
Therefore, if you have any values that you need to use again in PHP for the second request, you can either create them again, or receive them in the request data, or the first PHP script must have stored them somewhere persistent that you can retrieve them from, such as a session variable or cookie, or database.
It's not clear from your posted code, but presumably in the second request the function act1() gets called somehow and tries to insert the data into the database. It fails because neither $film or $conn have any values in them in this new request.
I suggest you solve it like this:
1) Create your connection object again, this is easy, and you need to re-connect to MySQL for this request anyway.
2) the film you're rating should be passed back from the browser in the form data.
This is the first script, to get the initial film data and render the ratings form to the page.
//re-usable function to connect to DB. Maybe move this out to a separate file so all pages can use it.
function getDBConn() {
return mysqli_connect('localhost','root','','filmsdb');
}
function show()
{
$conn = getDBConn();
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
$conn = null;
}
Your latest update doesn't show the form but I'm going to assume it's something like this, with an additional film hidden field. There should be suitable form tags around it as well.
<input type="radio" value="1" name="rate">
<input type="radio" value="2" name="rate">
<input type="radio" value="3" name="rate">
<input type="radio" value="4" name="rate"><input type="radio" value="5" name="rate">
<input type="hidden" name="film" value="<?php echo $film;?>"/>
<input type="submit" value="Rate" name="rsub">
Now is the second script, to be run when the rating data is submitted. You haven't shown how act1() is called but I'll assume you've got that covered.
function act1()
{
if(isset($_POST['rsub']))
{
$film = $_POST['film']; //get the film ID from the submitted form
$conn = getDBConn(); //assuming this script is in the same .php file as the first block, otherwise you'll need to move getDBConn into a separate php file and then include the file in each script.
$rate = $_POST['rate'];
$sqlr = "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn, $sqlr);
}
if ($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored';
echo mysqli_error($conn);
}
$conn = null;
}
P.S. I know it's just an example project, but if you make a real-life site please heed the comments above re SQL injection, and don't let your applications and websites log into your DB as "root" either - give them only the privileges they actually need.

Edit mysql database from "GET" index.php?id=XX

I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.

using _GET url link to delete a record from mysql database

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.

Categories