Hope some one can help me out here,
i created a system with more than 1 user, each user have a unique username and id.
My problem now is how can i set my system in such a way that when a user log in, the system will direct the user to view a particular row in the database based on their username or id.
My Code to Access the Database is:
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction WHERE username = '".$_SESSION['username']."' LIMIT 1");
if(mysql_num_rows($y) != 0){
echo "<table border=\"1\" width=\"800\" >";
echo "<tr id=\"bold\">
<td>No</td>
<td align=\"center\" width=\"120\">Account Owner</td>
<td align=\"center\" width=\"120\">Deposit Date</td>
<td align=\"center\" id=\"bold\" width=\"150\">Current Balance</td>
<td align=\"center\" width=\"150\">Available Balance</td>
<td align=\"center\">Account Status</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td>".$count++."</td>
<td id=\"color\" align=\"center\">".$z[1]."</td>
<td id=\"color\" align=\"center\">".$z[2]."</td>
<td id=\"color\" align=\"center\">".$z[3]."</td>
<td id=\"color\" align=\"center\">".$z[4]."</td>
<td id=\"color3\" align=\"left\">".$z[5]."</td>
</tr>";
}
echo "</table>";
}
?>
My Login Page Looks Like This:
<?php
session_start();
$_SESSION['username'] = $username;
$username = $_POST['username'];
$password = $_POST['password'];
if ($username&&$password)
{
$connect = mysql_connect("localhost","root","") or die("cannot connect!");
mysql_select_db("uloaku") or die("cannot find data base!");
$query = mysql_query ("SELECT * FROM keyaku WHERE username='".mysql_real_escape_string($username)."' AND password='".mysql_real_escape_string($password)."'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username==$dbusername&&$password=$dbpassword)
{
echo "Welcome $username";
}
else
echo "Invalid Password";
}
else
die("Invalid User");
}
else
die("Please Enter a UserName and Password.");
?>
So far my log-in is working as i want it, and my database retrieves information the only problems is that it retrieves all information which is in the database but i want it to retrieve information based on the username or id of the person that logs in
First of all, I bet this piece of code does not work at all:
$query = mysql_query ("SELECT * FROM keyaku WHERE username='$username'&&password='$password'");
... there is no such thing as && in MySQL, therefore the query will return empty result. If you want it to work, do it at least this way (prevents SQL injection, too!):
$query = mysql_query ("SELECT * FROM keyaku WHERE username='".mysql_real_escape_string($username)."' AND password='".mysql_real_escape_string($password)."'");
Second of all, you need some way to store your login information, so it can be reused later on. If you can use sessions, the simplest way is to store username (or whichever information is linked to the row you need):
$_SESSION['username'] = $username;
Then, in your first page, update SQL to read as follows (change the column ID per your needs):
$y = mysql_query("SELECT * FROM transaction WHERE username = '".$_SESSION['username']."' LIMIT 1");
... you don't even need the LIMIT 1 part if your username field in transaction table is indexed as a primary/unique key.
Related
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>
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id';";`
$resultset = mysql_query($sql);
$row = mysql_fetch_array($resultset);
I got specific userid from specific event column like eventid==> eid-01(us-0, us-3,...),
$num_row = mysql_num_rows($resultset);
while($row) {
for($i = 0; $i<$num_row; $i++) {
$sql = "SELECT userId, firstName FROM userinfo WHERE userId='$row[$i]';";
$resultset = mysql_query($sql);
$row22 = mysql_fetch_array($resultset);
$us_id = $row22['userId'];
$us_name = $row22['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
break;
}
$row = mysql_fetch_array($resultset);
}
On that code I got only one userid info but there is more userid against one event.
First of all, use if statement to check whether the returned result set contains any row or not, like this:
if($num_row){
// your code
}
Second, use a while loop to loop through the result set and display it's contents, like this:
while($row22 = mysql_fetch_array($resultset)){
// your code
}
And finally, please don't use mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead. And this is why you shouldn't use mysql_ functions.
So your code should be like this:
<?php
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id'";
$resultset = mysql_query($sql);
$row = mysql_fetch_array($resultset);
$num_row = mysql_num_rows($resultset);
if($num_row){
$sql = "SELECT userId, firstName FROM userinfo WHERE userId='" . $row['userId'] . "'";
$resultset = mysql_query($sql);
?>
<table>
<tr>
<td>User ID</td>
<td>First Name</td>
</tr>
<?php
while($row22 = mysql_fetch_array($resultset)){
echo "<tr><td>{$row22['userId']}</td><td>{$row22['firstName']}</td></tr>";
}
?>
</table>
<?php
}
?>
For better readability I have displayed the data in table cells.
Simple Solution
You need to get multiple userIds from eventmember table which have multiple users against each event. But you are fetching only once from that query with $row = mysql_fetch_array($resultset);, So you should get only one user, what you are getting now. Hence, the problem is, you actually have put the while loop in a wrong place. The loop should be set like this :
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id';";
$resultset = mysql_query($sql);
$num_row = mysql_num_rows($resultset);
if($num_row) {
while($row = mysql_fetch_array($resultset)) {
$sql22 = "SELECT userId, firstName FROM userinfo WHERE userId='{$row['userId']}';";
$resultset22 = mysql_query($sql22);
$row22 = mysql_fetch_array($resultset22);
$us_id = $row22['userId'];
$us_name = $row22['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
//You shouldn't use a break here. This will again give you single result only.
}
}
A Better Solution
Instead of using multiple queries to get the data from userinfo table, use JOIN to get all data with one query. Like this :
$sql="SELECT u.userId,u.firstName FROM eventmember e JOIN userinfo u ON u.userId = e.userId WHERE e.eventid='$event_id';";
$resultset = mysql_query($sql);
$num_row = mysql_num_rows($resultset);
if($num_row) {
while($row = mysql_fetch_array($resultset)) {
$us_id = $row['userId'];
$us_name = $row['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
}
}
The Best and Most Secure Solution
As you should have already known mysql_* functions are removed in PHP 7 and this functions are highly harmful for your security. So, you should either move to PDO or mysqli_* functions. I am giving here an example with mysqli_* functions and additionally I am fetching all rows at once instead of doing fetch for each row, which is better for performance.
//First setup your connection by this way.
$link = mysqli_connect(localhost, "my_user", "my_password", "my_db");
//Now you can use mysqli
$sql="SELECT u.userId,u.firstName FROM eventmember e JOIN userinfo u ON u.userId = e.userId WHERE e.eventid=?;";
$stmt = mysqli_prepare($link, $sql);
$stmt->bind_param('s', $event_id);
$stmt->execute();
$resultset = $stmt->get_result();
$resultArray = $resultset->fetch_all();
$num_row = count($resultArray);
if($num_row) {
foreach($resultArray as $row) {
$us_id = $row['userId'];
$us_name = $row['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
}
}
mysql_fetch_array() will retrieve a single result from a result set. Therefore you'll need to wrap it in a loop to get each row/result.
Here's an example I ripped straight from the PHP documentation:
while ($row = mysql_fetch_array($result)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]);
}
In your case you'd wrap the HTML code in the while loop.
An additional improvement would be to ensure that $resultset is a resource; mysql_query() can return false if your query is invalid (and true in other success cases like INSERTS). You can also use mysql_num_rows() to determine if you have >0 rows to display (and custom display a 'No rows returned' message).
Perhaps more importantly is that mysql_* functions were deprecated in PHP 5.5.0, and additionally removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL.
By continuing to write mysql_ code you'll make upgrading substantially more difficult for yourself. It's also worth noting that 5.5 will also reach security EOL in 6 months, leaving you to rely on your OS vendor to backport security updates from then on.
I have a small database that will show data being updated as 0 and not as 1. When I try to run the following sql query
Database PHP
// Connect To DB
$hostname="localhost";
$database="xxxx";
$username="xxxxx";
$password="xxxxx";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database)
or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = 'SELECT * FROM mods ORDER BY id where updated="0"';
$result = mysqli_query($conn, $query);
#$num_results = mysqli_num_rows($result);
I have tried wrapping and not wrapping the 0 in '' and "".
Currently it just loads the HTML table without data. If I remove the where statement, it pulls fine.
HTML PHP
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
?>
<tr>
<td style=""><?php print $row['mod_name']; ?></td>
<td style=""><div id"tdcenter" style="width: 44px;white-space:nowrap;overflow: hidden;text-overflow: ellipsis;text-align:center;"><?php print $row['mod_version']; ?></div></td>
<td style=""><?php print $row['time']; ?></td>
</tr>
<?php
// end loop
}
?>
Please try these and check which one works for you:-
As #BigRabbit says :- $query = "SELECT * FROM mods ORDER BY id where updated='0'";
create a variable $update = 0;
and now append it to your query $query = "SELECT * FROM mods ORDER BY id where updated=".$update;
Another attempt is swapping ORDERBY and WHERE clause.
The syntax on your query is wrong try this:
$query = "SELECT * FROM mods ORDER BY id where updated='0'";
here's the script im having issues with..
I'm making an in-game Kills high-score board for my game, and I'm trying to make this mysql query work but i can't get it.
Can anyone please help me.
if($i < $top_hiscore && !in_array($row["playerName"], $banned) && !in_array(ucwords($row["playerName"]), $banned)) {
if($i & 1) {
echo '<tr class="row row1">
<td class="rankCol">'.$i.'</td>ITS HERE
<td class="alL">'.BBCode($row["playerName"]).'</td>
<td class="alL">'.getKillsFor('.$row["playerName"].').'</td>
</tr>';
} else {
echo '<tr class="row row2">
<td class="rankCol">'.$i.'</td>
<td class="alL">'.BBCode($row["playerName"]).'</td>
<td class="alL">'.getKillsFor('.$row["playerName"].').'</td>
</tr>';
}
}
and here's the getkillsfor method... Which is what is incorrect
function getKillsFor($name) {
$kquery = mysql_query ("SELECT * FROM skills WHERE playerName ='".$name."'") or die(mysql_error());
$query = mysql_query($kquery);
$row = mysql_fetch_row($query);
$shoeRating = $row[0];
return $shoeRating[$name];
}
Just so you know, mysql_query is deprecated. Use PDO and prepared statements instead. Avoid sql injection with people setting $name to be '; or 1=1; # )
The output of mysql_query is a resource, that's the thing that you should send to mysql_fetch_row
So this
$kquery = mysql_query ("SELECT * FROM skills WHERE playerName ='".$name."'") or die(mysql_error());
$query = mysql_query($kquery);
$row = mysql_fetch_row($query);
should be
$result = mysql_query("SELECT * FROM skills WHERE playerName ='".$name."'") or die(mysql_error());
$row = mysql_fetch_row($result);
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.