pull specific table row column data to output in html using php - php

how do i pull data from my database table and put that data into a readonly textinput in a form for a user to see.
<input readonly type="text" name="em1" id="em1"/>
for this specific field i want to pull the data from a column called wmyt000 in the row of the currently logged in user using a $username variable with session that i created to get the current logged in users username in a table called cash_flow_plan
im using mysql and php
i havnt attempted to try anything yet. i was looking into mysql_fetch_array but that wants to display all of the users information for their row.

i havnt attempted to try anything yet.
ya. well, if you had, you'd know that you can do more with it than you think.
if you write a query limiting your results, then you're going to get what you want.
$query = "SELECT wmyt000 FROM cash_flow_plan WHERE username = '$username'"
$row = mysql_fetch_row($query);
print_r($row); // now you can see the structure of your array. access it accordingly.

Related

mysql - Query to display record just added

I have two pages. One is a form that I use to simply input data that will be sent to my database and the second page that actually takes the data inputted into the form and sends it to the database and is supposed to display the information that I've just added.
Everything works fine, however I'm struggling with the query slightly. What I need it to do is display all the information for the last data inputted to the database.
The query I currently have just displays the data with the highest ID:
$sql = "SELECT * FROM Results ORDER BY ID DESC LIMIT 1";
So as an example I would be left with the following information after completing my form:
Success! Data being saved:
ID = 900 Amount = 206 Date = 2016-12-26
This is obviously just showing the data with the highest ID, but since the ID and all the data fluctuates, I need it to just show the data that has just been inputted.
I came accross this: Query to select newly added records only. But I don't believe this soultion to be viable as the database is external and I don't want to be creating new tables.
I was thinking that it might be possible to assign a hidden value to each newly added record via the query. e.g. New 1, New 2, New 3 etc. Then printing the latest record for New. However, I couldn't find anything on how to do this.
Any help would be greatly appreciated!
You must use this method to have very correct value:
Input form must send to another file that do inserting (we call it here insert.php)
insert.php must insert the data after validation and after that you can fetch the last ID number from database. Depending on the method you are working with it can be different. for example if you are using PDO you can get it by PDO::lastInsertId
after getting the ID you need to forward it to the viewing or editing page. for example view.php?id=LastInsertId. This forward have some reasons:
Codes can be cleaner.
We prevent refresh and resend inserting. for example if you do inserting inside view.php and user hit F5 to refresh the page, The insertion happening again.
This is the whole idea. you can use this method for only one page:
page.php?do=new
page.php?do=insert
forward to the page.php?do=view&id=lastInsertID
why you trying to get just inputted data from database? you can do it using HTTP POST/GET method easily.just send data as parameters and show them in second page.
If you already have the data you are inserting, you don't need to run a query to get it back from the database again, you could just ensure that the query was successful and display the data directly. Anyways:
You can get the insert ID from the last insert using the MySQLi object. For example:
$sql = "<your insert statement>"
$conn->query($sql);
$last_id = $conn->insert_id; //Id of the row you just inserted
$sql = "SELECT * FROM Results WHERE id=$last_id";
This is assuming you do the insert in the same page that you display the result.

How to select a persons lastname in php from mysql table and put it in a $_Session variable

I want a straightforward answer with an example (NO LINKS please) to see how I can retrieve a specific person's last name from a table in a MySQL database using PHP and save it into a variable (i.e. $_Session). I have been looking for this question and I don't get anything related to one row in PHP. If this can be done better with mysqli* functions then I would be glad to see it.
Example
$getData = "SELECT lastname FROM person WHERE name='$name'";
$getData_q = mysql_query($getData) or die('Error');
Then i want something like this:
$_SESSION['lastame']=$getData_q; <- Please correct me,
I'm not asking to get a lastname from an input, I'm asking to get it from the table person in the database with the SELECT.
Use
$getData_q = mysqli_fetch_object($getData_q);
$_SESSION['lastame']=$getData_q->lastame;
But ensure that that num rows is greater than 0 and data would return a single row.

Cakephp retrieve info from database

I'm having some problems understanding the connection to the database in CakePHP.
I have a table called user (which was taken from the CakePHP tutorial website) I added another row to the table called "bio" I am able to insert text into the bio but i'm not able to retrieve it.
I've managed to retrieve all the other rows by:
$name = CakeSession::read("Auth.User.username");
$mail = CakeSession::read("Auth.User.email");
$created = CakeSession::read("Auth.User.created");
$id = CakeSession::read("Auth.User.id");
but for some reason it won't work with the bio.
Do I need to add anything to controllers to be able to this? Or is it a variable that I need to set?
Thank you!
As #sgt BOSE said. Using CakeSession::read("Auth.User") you will get session data of your current logged user.
$current_user_data = $this->User->FindById(CakeSession::read("Auth.User.id"));
This will return current (logged) user data from database.

Cannot select all results from a table depending on another table (relational DB) in PHP and MySQL

I am trying to finish this website I am currently creating, but I am kind of stuck.
I want to create a table called "orders" in my DB. I want this table to be related to my users table so that when the user goes to his "orders.php" page (once logged in already) he sees all his current and previous orders.
These would be my table fields/cols:
id
username
ordernumber
description
quantity
total
This is my approach:
Whenever a new order is created, insert all the table fields/cols depending on the user's choice (selected stuff for the order), but the username would be the only value gathered from a $_SESSION or $_COOKIE variable, which holds the username. Then, once the user goes to orders.php, I will execute a query to show all the orders that only that username has ordered. Please note that I do sanitize all my input/output and I do not store sensitive data in my cookies. My system is designed so it only uses the session as the method of authentication, therefore you need to login every time you close the browser but that is fine.
1) Is this a safe approach? Do you have any suggestions/comments?
2) Could you help me construct the query?
I haven't really worked with relational databases, so I am kind of lost. How can I call all the orders from table "orders" where username = "username from the session"?
So far I have this:
"SELECT * FROM orders WHERE username = ? " //(Using PDO)
I know that this will work but my concern is in case of getting a session hijacked or something like that, then a user would be able to retrieve any users' orders, or not?
Thank you for explaining this a little bit further and helping me out!
Cheers!
Be careful! Please don't create a plain text cookie containing a human-readable user id (like user2345995 or OllieJones). It's far too easy for a badguy to fake a cookie like that just by guessing, and then your users' information leaks out.
You're working in php. Therefore you can use php's session mechanism to store your userid and other values. php uses hard-to-guess session ids (SIDs) and stores them in either a cookie or as a sid=1234abcd9875 parameter in URLs.
For the sake of your system's integrity, please read up on this. It's actually a pretty well-designed feature and it's been in the wild for fifteen years or so: it's debugged.
http://php.net/manual/en/session.idpassing.php
If you're using the session system, you basically do this in your first page, your login page.
session_start();
...
$_SESSION['username'] = $username; /* which you get by logging in */
...
On your order lookup page you do something similar to retrieve the username and use it in a query.
session_start();
...
$orderstmt = $pdoconn->prepare("SELECT * FROM orders WHERE username = :username");
$orderstmt->execute( array(':username' => $_SESSION['username']) );
...
while ($row = $orderstmt->fetch()) {
/* use the row's data */
}
$orderstmt->closeCursor();

How to create a Profile URL for a user using $_GET['id']

Can someone advise me if I am performing the below steps correctly:
When a user wants to register on the website, register.php handles his/her request. Below is some of the code from register.php:
$sql="INSERT INTO Members (fldFullName, fldEmail, Password, Gender, DOB)
VALUES
('$fname','$email','$pass', '$gender', '$date')";
Particularly when I wrote the above code, I was somewhat new to PHP/MySQL and still am. Therefore, I made all of the fields above manually in the table via phpmyadmin. Furthermore, I also added the ID field manually via phpmyadmin, as the first field with auto increment and primary key of course. Why I did it manually, I can't remember the reason of. But I'm pretty sure that this may be the reason why I'm having problems.
What I'm trying to do is, when a user registers on the website, I want a profile URL to be created for him/her. For example, the field in the table could be named ProfileURL, whereas the actual value could be http://www.domain.com/profile.php?id=1, where the id is inherited from the actual ID in the table. How can I do this with my above code? Did I do something wrong when I decided to save all the fields manually via phpmyadmin? Note: I've also been creating tables, databases, fields manually via phpmyadmin. However, its values are INSERTed automatically of course. Am I even on the right track?
Thank you.
As stated above, you don't need to save a profile URL to the database. I'm guessing all profile URLs are going to follow some standard form (i.e. www.example.com/profile.php?id=1)?
Well, if you saved all of those in your database and then you decided you were going to change the format to something like www.example.com/profile/1 you're going to have a lot of out-of-date data in your database. You're going to have to go through each record and update it, and that could be dangerous on a database table with say, millions of rows.
Therefore, the solution is to have a script that takes a parameter. Say profile.php. As above, you would check for the profile using the data in the $_GET array:
<?php
if (isset($_GET['id'])) {
$id = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM members WHERE id = '$id' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows() > 0) {
$member = mysql_fetch_object($res);
// handle displaying of member's profile here
}
else {
// member does not exist with ID
}
}
?>
That way, if you decide to change the script name or use search engine-friendly URLs, you don't need to change your database structure.
In profile.php, check for $_GET['id'], then if it exists, use a SELECT query for the same ID in the database. It would look something like this.
<?php
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM Members WHERE ID = ' . $id;
// Then the rest of the code to check the results goes here
}
?>
A user with an ID of 1 would be profile.php?id=1
You are doing right. Now write SQL like this:
$sql = sprintf("SELECT * FROM Members WHERE ID=%d", mysql_real_escape_string($_GET['id']));
And you'll be able to get userdata by $_GET['id']. Remember to use mysql_real_escape_string to protect your queries against SQL injection. sprintf is also a good thing to substitute right data types like numbers or strings.
You don't heed to save profile url.
You have to build it dynamically.
Because most of the url remains the samy, only id is changing.
So, get id from the database and add it to the url.

Categories