Mysqli to display link to profile page - php

I'm looking for the best way for a user to be able to click on a link displayed on each row from mysql results page which will take them to a page which displays all the with regards to the id from that row.
HTML TABLE
<?php
$sql = "SELECT firstName, lastName, id FROM users";
$result = $conn->query($sql);
echo "<table border='1px'>";
echo "<tr><th>First Name</th><th>Last Name</th><th>Link</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['firstName']}</td>
<td>{$row['lastName']}</td>
<td> LINK HERE </td>
</tr>";
}
} else {
echo "0 results";
}
echo "</table>";
?>
USER PAGE
$sql = "SELECT firstName, lastName FROM users WHERE id="????";
$result = $conn->query($sql);

You can pass the information in the URL query string:
http://www.example.con/user.html?id=123456
Where the '123456' is the ID in the database for the user. This will be available in the GET array;
$_GET['id']
So now you can use that variable in your query to get the user's info for the page
Warning
Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!
EDIT
I also noticed that you had this:
<td> LINK HERE </td>
Here is how your link would look:
<td>link text</td>

Related

PHP - Looping Through rows in MySql and displaying a field based on user's click

My first question on Stack Overflow, so please forgive if I make any mistake.
I have a database, in which I store the User Id and the title and corresponding content. Then in a PHP page, I loop through the rows of the table and display the title of the content in an anchor tag.
The problem is, When the user clicks on a specific title, he should be redirected to new page where the content corresponding to the title which he clicked is displayed.
Could you please guide me as to how to achieve it?
Thanks.
Here is the code that I've tried.
<?php
$counter1 = 0;
$sql = "SELECT * FROM blogdata2";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
echo "<a style='color: #E64A19;' href='#'/>".$arrayContent[$counter1]['title'];
echo "<br/>";
$counter1++;
Try like this...
$sql = "SELECT * FROM blogdata2";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
echo "<a style='color: #E64A19;' href='newpage.php?content=".$row['content']."'>".$row['title']."</a>";
echo "<br/>";
}
and in newpage.php
<?php
$content=$_GET['content'];
echo "<p>".$content."</p">;
But following way is best...
$sql = "SELECT * FROM blogdata2";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
echo "<a style='color: #E64A19;' href='newpage.php?id=".$row['id']."'>".$row['title']."</a>";
echo "<br/>";
}
and in newpage.php
<?php
$id=$_GET['id'];
$sql="SELECT * FROM blogdata2 WHERE id='$id'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "<p>".$row['content']."</p>";

Mysqli query multiple tables

I'm trying to make a query that then displays certain results based on previous queries
The idea is that when someone logs into the page, it gets the session username and and saves it to a variable, from there the first query selects a row based on the session username, gets that value and does the same in the second query but on a different table this time getting the row based on the result from query 1 and query 3 is same as two and then its meant to echo it out
here's the code
$con = mysqli_connect("localhost","root","","boats4u");
$search = $_SESSION['myusername'];
if(mysqli_connect_errno())
{
echo "Failed to connect to database". mysqli_connect_error();
}
$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='$pre_res'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '$result'");
echo "<table border='1'>
<tr>
<th>Client No</th>
<th>Boat No</th>
<th>View Date</th>
<th>Comments</th>
</tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>". $row['clientNo']."</td>";
echo "<td>". $row['boatNo']."</td>";
echo "<td>". $row['viewDate']."</td>";
echo "<td>". $row['comment']."</td>";
}
echo "</table>";
?>
this is what displays
Notice: Array to string conversion in
E:\Download\Xampp\htdocs\owner.php on line 29
If I remove the first query then it no errors but obviously the search doesn't work then
any help appreciated
You should do one query and also parametize the search parameter. Something along the lines like:
$stmt = $con->prepare('
SELECT boatviewing.*
FROM boatowner owner
LEFT JOIN boatforrent ON boatforrent.ownerNo = owner.ownerNo
LEFT JOIN boatviewing ON boatviewing.boatNo = boatforrent.boatNo
WHERE owner.email = ?
');
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
Such code is normally more robust against SQL injection and it's also easier in case you change your database layout.
Next to that you actually run one query instead of three which allows the database to optimize data-retrieval and keeps roundtrips between the PHP script and the database server low.

mySQL expects parameter to be string

Ok, so I basically have a form where users can fill out information, on form submission the information gets loaded into my SQL database.
There is an "administrator" page that displays all users that are in my User Table in my DB.
All is well and good that all works perfectly but my problem is that I made the userId's clickable so that when I click on the userId that specific entry will be loaded from the db.
I can't get the userId that I selected printed on the screen.
Here's my Admin page:
<html>
<head>
</head>
<body>
<?php
//Step 1: Set the connection object equal to our database
$conn = mysql_connect("localhost", "root", "") or die (mysql_error());
//Step 2: Set the databse you want to use
mysql_select_db("assignment_3", $conn);
//Step 3: Write sql that we want to run against the database
$sql = "select id, firstName, lastName, emailAddress from usertable";
//Step 4: Run the sql statement against the database connection object we created $conn
$result = mysql_query($sql, $conn) or die (mysql_error());
//STEP 5: Process the result set $result
print "<table border='1'>";
print "<tr>";
print "<td>id</td>";
print "<td>firstName</td>";
print "<td>lastName</td>";
print "<td>emailAddress</td>";
while ($row = mysql_fetch_assoc($result)) { // this is getting each row that was returned
$clickId = $row['id'];
print "<tr>";
print "<td><a href ='showUser.php?userId=$clickId'> $clickId </a></td>";
print "<td>$row[firstName]</td>";
print "<td>$row[lastName]</td>";
print "<td>$row[emailAddress]</td>";
}
print "</table>";
?>
</body>
</html>
If you run this page all the users in the db are loaded and displayed in a table and all of their userId's become clickable links when clicked take you to the showUser.php page which displays the information for the user that was selected.
Here is the code for the showUser.php page. I need to grab the userId with the GET method from the URL and then query the DB against that ID so show the user information.
I'm really stuck and need some help.
<html>
<head>
</head>
<body>
<?php
$id = filter_input(INPUT_GET, "userId");
//Make db connection
$conn=mysql_connect("localhost","root","")or die(mysql_error());
//Step 2: select your db to use
mysql_select_db("assignment_3",$conn);
//Step 3: Write the sql that we want to run against the database
$sql = mysql_query("select id, firstName, lastName, emailAddress, phoneNumber, underGradSchoolId, gradSchoolId, securityQuestionId from usertable where id='$id'");
$result = mysql_query($sql,$conn)or die(mysql_error());
print "<table border='1'>";
print "<tr>";
print "<td>id</td>";
print "<td>firstName</td>";
print "<td>lastName</td>";
print "<td>emailAddress</td>";
print "<tr>";
print "<td>id</td>";
print "<td>firstName</td>";
print "<td>lastName</td>";
print "<td>emailAddress</td>";
print "<td>phoneNumber</td>";
print "<td>underGradSchoolId</td>";
print "<td>gradSchoolId</td>";
print "<td>securityQuestionId</td>";
print "</table>";
?>
</body>
</html>
You are using mysql_query twice:
$sql = mysql_query("select id, ...");
$result = mysql_query($sql,$conn)or die(mysql_error());
Which should be (renamed so it is like the first code you posted)
$result = mysql_query("select id, ...") or die(mysql_error());
$row = mysql_fetch_assoc($result);
Now you can print the values like
print "<td>".$row['id']."</td>";
Also keep in mind that mysql_* functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer on SO for more information.
First verify that your getting the value you expect with $id. After step 3, print $sql and make sure it ends with "where id = '{selected id}'"

Get the data of specific user in PHP

Now I have created a login form with a session, what I need now that when the user login with his username and password, get his data such as name, about etc.. and put it in the welcome page.
Currently I have created this code but this code get all users data,
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("usersdata") or die(mysql_error());
$data = mysql_query("SELECT * FROM userid")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['Name'] . "</td> ";
Print "<th>Username:</th> <td>".$info['Email'] . " </td></tr>";
}
Print "</table>";
?>
I hope to find a way to do that. :D
Since you already created a login form with session then you get the data for the current logged in user by doing this:
$_SESSION['userid']: Should be filled in the login page.
$_SESSION['userid'] = $id
Learn more about the sessions: PHP Sessions W3schools
And then:
$query= mysql_query("SELECT * FROM `userid` WHERE `id` = '".$_SESSION['userid']."' ")or die(mysql_error());
$arr = mysql_fetch_array($query);
$num = mysql_numrows($query); //this will count the rows (if exists)
HTML
<html>
//...
<?php if($num > 0){ ?>
<table border="1" cellpadding="3">
<tr><td colspan="2" align="center">Your Info</td></tr>
<tr>
<td>Name: <?php echo $arr['Name']; ?></td>
</tr>
<tr>
<td>Email: <?php echo $arr['Email']; ?></td>
</tr>
</table>
<?php }else{ ?>
User not found.
<?php } ?>
//...
</html>
Although you should use the mysqli_ extension, rather than mysql_, you would want something like:
$result = mysql_query("SELECT * FROM userid WHERE username = '" . $username . "'")
or die(mysql_error());
if(mysql_num_rows($result) == 1) {
//Found the user
$row = mysql_fetch_array($result);
//Results can be accessed like $row['username'] and $row['Email']
} else {
//Too few or too many records were found
}
Note: I've used username='$username' as an example. It would be best to track the user's ID from the login process as the ID refers to a specific row.
$data = mysql_query("SELECT * FROM userid")
Should be
$data = mysql_query("SELECT * FROM userid WHERE Name='$selectedName'")
Of course you need to define $selectedName
I also recommend you read http://dev.mysql.com/doc/refman/5.0/en/select.html to learn about some fundamentals.
Your example code retrieves all users from the database and loops through the data using a while loop.
To get the user that has logged in you need to change your query that fetches the data.
I'm assuming you have a primary key in your table and know the id because the user already logged in.
$data = mysql_query("SELECT * FROM userid WHERE id={$userid}");
$info = mysql_fetch_array( $data );
echo $info['Name'];
$info will now contain all the user info for 1 user, you need to fill $userid with the actual id from the user that is logged in.

retrieve single row data in mysql using php

I created a website that has multiple logins and unique informations to it.. i want to retrieve the data from one user. example my username is qwert and my password is 1234, I want to retrieve his unique information to the database. I used the sample code in w3schools and it selects all the data but all I want to do is to retrieve the data from the user which is only logged in.
can anyone help me about this? any help will be much appreciated.
mysql_select_db("xone_login", $con);
$result = mysql_query("SELECT * FROM admin WHERE username = '$myusername' ");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['overtime'] . "</td>";
echo "<td>" . $row['daily_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Replace the code in SQL in that tutorial with this (and adapt the table and column names) one:
SELECT * FROM USERS where name ='qwert' and pass = MD5('1234')
And take care at sanitizing your variables in order to avoid SQL injection attacks !
You need to use a where clause
Also you will need to specify limits on the query to restrict the result set to 1 record
$select = "SELECT * FROM usertable WHERE username = '$user' LIMIT 0, 1";
$query = mysql_query($select) or die(mysql_error());
$result = mysql_fetch_assoc($query);
//Prints the array
print_r($result);

Categories