Link in PHP using SQL generated name - php

I have written the following code to generate information from an SQL database:
<?php
$search1 = "SELECT Name FROM users";
if($mysqli->query($search1) == TRUE)
{
echo "You have successfully searched the request";
}
$result = $mysqli->query("SELECT Name FROM users");
echo '<table border=1px>';
echo'<th>Name</th>';
echo $row;
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
echo'<tr>'; // printing table row
echo '<td>'.$row['Name'].'</td>';
echo'</tr>';
}
echo '</table>';
?>
This generates a list of names in the table. There are other columns in the table such as Country, Email, Hobby and Date Signed up. All of which are VARCHAR except the last which is of type DATE. I am trying to figure out code so that when I click on one of the generated names, the rest of the information (Country, Email etc,) is shown.

Just doing something like:
echo '<td><a href=\"userinfo.php?username='.$row['Name'].'\">'.$row['Name'].'</td>';
And then in userinfo.php, read the $_GET['username'] parameter to make a query similar to the one you have above, something like this:
$search1 = "SELECT * FROM users where Name=?";
And then setting the parameter $_GET['username'] to the prepared statement (if you want to avoid MySQL injections).

You can use the following SQL to get only the information that will be used in your listing page, in your case that would be identifier and name columns (you have identifier column, right? if not, check again your database structure - there's something wrong).
SELECT ID, Name FROM `users`
And then you can create extra page in your application, e.g. show.php where you will pass the identifier of each record as $_GET parameter, e.g. show.php?id=5
And there you should create another query:
SELECT * FROM `users` WHERE `ID` = $_GET['id']; /* that's not secure, read below */
Once you have that data, you can list it and you're done.
If you want to create one-page application, you can hide available info with CSS and display it when user clicks on username. Read about jQuery. You can even use AJAX. It's your choice.
If you want to make everything better, you can try use PDO.
Also, be aware of these vulnerabilities:
SQL Injections
Cross-site scripting

Related

SELECT column mysql

I am in a little bit in doubt, if I am on the correct path here. I have a mysql database, where I have login details of users. I am making a profile page, where I would like the informations on a user is shown to the user. I am now trying to return the firstname there is a column in the database. Am I on the correct path with this code?
<td>
Firstname
<?php
$stmt = $mysqli->prepare("SELECT firstname FROM login");
$stmt->execute();
$fname = null;
$stmt->bind_result( $fname);
while($stmt->fetch()) {
$firstname = // Code here
echo $firstname;
}
$stmt->close();
$mysqli->close();
?>
</td>
Update:
I tried to make the code a little bit smaller. This code actually retrives users, but it is all the users in the database, and not only the user I am logged into with. Should the SELECT query be asigned with the primarykey, if I only need the firstname on the current user I am logged in as?
<td>
Firstname
<?php
$sql ="SELECT firstname FROM login;";
$res = $mysqli->query($sql);
//print($res);
if($res){
while($row = $res->fetch_assoc()){
echo $row['firstname'];
}
}
?>
</td>
You are on the correct path but you need to assign your array to a variable so you can print adding your column name in the scope and remove the bind of $fname
//$stmt->bind_result($fname);
while($column = $stmt->fetch()) {
$firstname = $column['firstname'];
echo $firstname;
}
Or you can just use the variable you bind before
$stmt->bind_result($fname);
while($stmt->fetch()) {
echo $fname;
}
You could optimize your query and limit tresult to only one user by adding a WHERE condition to your query, you can use user ID for example
SELECT firstname FROM login WHERE userid = 1
If you're playing around with PHP and trying to learn how things work, you're on a great path. If you're planning on deploying this code to the internet, you have a few issues:
Your markup seems off. Why are you putting all of the first names in a single <td>?
You shouldn't have a SQL query happening inside of a markup. What if you want to show results from a cache or a text file some day? Ideally you wouldn't even mix PHP and HTML. Some folks use PHP's built-in templating abilities, but it's generally preferred to use a template language like jade or twig.
Your code alignment isn't consistent.
But if you're just seeing what PHP can do, good job. Keep trying stuff out. It's the best way to learn for most people. Others like reading a book, then trying stuff.

Display single record based from the URL (id)

I have a website where it displays all of my records. I can click on an individual record and it gets the student_id of that record and updates it to the URL eg. view_student.php?id=12.
It then takes me to a new page where I want it to display all the information about that record, in this case, show all information about student number 12, but none else.
I haven't a clue how to carry out the statement to display all of the information for that record, this is what I have so far:
if (isset($_GET['student_id'])) {
echo $row['student_name'] . $row['student_age'] . $row['student_gender'];
}
This is a standalone page with nothing else on it. view_student.php simply uses a require function to this script. This code does not display anything, nor does it display any errors. I'm using PDO and I have made sure I'm connected to the database.
My guess is that I will need to use a WHERE clause but I'm just not too sure
Thank you
You can use below PDO query to fetch your data
$statement = $db_con->prepare("select * from student where student_id = :student_id");
$statement->execute(array(':student_id' => $_GET['student_id']));
$row = $statement->fetchAll(PDO::FETCH_ASSOC);

Individual Username from a Database

I have a database running and I'm currently printing out in a website, in a "php block" the usernames of the database. I achieved it with this
if ($db_handle) {
print "Database ISSSSS Found ";
$SQL = "SELECT * FROM `database.com`.`users`";
$result = mysql_query($SQL);
//print $result;
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['username'] . "<BR>";
}
mysql_close($db_handle);
}
However this gives me a giant string of all the users (I currently have 4). How do I make it so its just the individual user accessing their profile through the website
Typically, when someone logs in, you would store non sensitive information about the user in the session. This way, you can get to it quickly without needing to make database calls on every page. For instance, if you wanted to show their username in the pages header, you would always have their username handy to do so. Then, when they go to view their profile, you can use that username you stored as part of your SQL WHERE clause to pull in information pertaining only to that specific user.
Use WHERE username = 'yourusername' in your SQL query.
That shall fix your problem

Printing an HTML page with unique number

I am having a php page in which i have captured different values from the previous page, There is also a print button, Which prints all these fields including the unique number. When user clicks on the print button record will be inserted in database and print window displays on the screen. But the problem is there is a unique number on html page, For example if two persons are login at the same time, The will get same unique number, and both will be able to print the same page having same unique number.
How i can control this issue, I also tried to redirect the user to the previous page but its not working.
Here is my php page, Which i am calling using ajax
<?php
$conn = mysql_connect('localhost','','') or die ("");
mysql_select_db("") or die ("Database Problem");
$query = "select * from print where a = $a;
$result = mysql_query($query);
if(mysql_num_rows($result) == 0)
{
$query = "INSERT INTO print () VALUES ()
$result = mysql_query($query) or die();
if(mysql_affected_rows()<>1)
{
header ("Location:mainpage.php?uniquenumber=xy");
}
}
you can use unisid http://php.net/manual/en/function.uniqid.php
To generate an unique id
What is this uniquenumber needed for in the client side? I mean having it accessible and editable for the users is kinda dangerous if it's an important value.
If you just need this number to tell apart the different entries in the print table, why not just use and auto_increment index for this table?
Another solution would be session variables. When a user succesfully logs in generate this unique ID based on multiple variables (username, time, browser), that will ensure there won't be repeated values for this ID. Then store the variable like this:
session_start();
$_SESSION['ID']=$unique_ID;
You can then read it in any other PHP script like this:
session_start();
$unique_ID=$_SESSION['ID'];
You can validate the unique number before inserting to database ( Before Printing also ). If the unique no is exist, throw a error message "unique no is already used " and give another unique number ( By loading the HTML Page again or doing something else ).

Displaying name instead of ID PHP MySQL

I need something simple; I have page where a user clicks an author to see the books associated with that author. On my page displaying the list of books for the author, I want a simple HTML title saying: 'The books for: AUTHORNAME'
I can get the page to display author ID but not the name. When the user clicks the link in the previous page of the author, it looks likes this:
<?php echo $row['authorname']?>
And then on the 'viewauthorbooks.php?author_id=23' I have declared this at the start:
$author_id = $_GET['author_id'];
$authorname = $_GET['authorname'];
And finally, 'The books for: AUTHORNAME, where it says AUTHORNAME, I have this:
echo $authorname
(With PHP tags, buts its not letting me put them in!) And this doesnt show anything, however if I change it to author_id, it displays the correct author ID that has been clicked, but its not exactly user friendly!! Can anyone help me out!
You could pull the author_id from the query string as you did using $_GET but beware you will need to validate what is coming through by the query. I hope you can see that without validation how bad of a security hole this is.
I am at work at the moment, but this is a quick example that should give you what you need without sanitizing your query.
$id = intval($_GET['author_id']);
// of course, perform more validation checks
// just don't assume its safe.
$sql = "SELECT authorname FROM authors_tb WHERE author_id=" . $id;
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "The books for: " . $row['authorname'];
}
The reason why your approach wasn't working was because you utilize the $_GET URL parameter passing for author_name where you weren't supplying the parameters in the URL, just the author_id.
You don't send it in the query string, thus you can't get it from the $_GET array.
Just request it from the database using id.
An important note: Always use htmlspacialchars() when you display the data, coming from the client side.
This is because you do not define the author name in your get.
You should make the following your url:
<?php echo $row['authorname']?>
Or rather select the data from the database again, on the new page, using the ID you retrieved from the URI.
Author name won't be in $_GET. As your code stands, you only use it as the link title. It is no where in the address. Try this instead:
<?php echo $row['authorname']?>
It would be better to re-request it from the database using the author_id though.
EDIT:
To explain the problem in more detail. You have two pages, the new.php page and the viewauthorbooks.php page. You're sending users from the new page to the view page using the link you posted, right?
The problem with that is, your link assigns one variable in get. Here's the query string it would generate:
viewauthorbooks.php?author_id=13
What that will do is send the user to viewauthorbooks and place the value '13' in the $_GET variable: $_GET['author_id']. That is why the author_id is there and displays on viewauthorbooks. However, authorname is never passed to viewauthorbooks, it isn't in $_GET['authorname'] because you never set $_GET['authorname']. If you want it to be in $_GET, then you need your query string to look like this:
viewauthorbooks.php?author_id=13&authorname=bob
You can accomplish that using the new HTML code for the link I posted above. Look at it closely, there's a key difference from the one you have now.
However, it is generally discouraged to pass data through GET, because the query string is displayed to the user and it leaves you open to injection attacks. A better way to do this would be to use the author_id you are already passing to viewauthorbooks.php to retrieve the authorname from the database again. You can use the same code you used on the new.php page.

Categories