retrieve single row data in mysql using php - 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);

Related

Query that looks for current user in table? php, sql

I am using php to query a sql db/table to retrieve a message which is on the same row as the current user.
I want to write a query that looks for the current session user in the table, and displays all info in all rows matching their username.
$user = $_SESSION["sess_user"];
$sql=mysqli_query($con, "SELECT * FROM Mail WHERE recipient_username ='".$user."'");
i cannot find the proper arrangement of fetching and displaying, and could use a pointer! thank you for your time.
I have been looking for the answer to this, and I'm sure there is one out there, so if someone has a link, it is more than welcome.
i got it. thanks guys.
$user = $_SESSION["sess_user"];
$sql=mysqli_query($con, "SELECT * FROM Mail WHERE recipient_username ='".$user."'");
if($sql){
$result = mysqli_query($con, "SELECT * FROM Mail WHERE recipient_username ='".$user."'");
while($row = mysqli_fetch_assoc( $result)){
echo'<table border="1" ><th >Message Date</th><th>Sender</th><th>message</th>';
echo '<tr><td>'.$row['msg_date'].'</td>';
echo '<td>' .$row['sender_username']. '</td>';
echo '<td>' .$row['sender_message'].'</td> </tr>' ;
echo '</table>';

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.

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.

Some error in my mysql_fetch_assoc

I am trying to create a rumour-based website. In one part of the site, there is a working feature where you are post rumours and the rumours are shown.
But i am working on the homepage so that the two latest rumours are placed into a table. With my code below, there is a table with no rows, despite data being in the mysql table, and this error message:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /websites/123reg/LinuxPackage22/th/eq/li/theqlick.com/public_html/leeds.php on line 212
Any idea? My code is below:
$query = "SELECT * FROM rumour ORDER BY id DESC";
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
echo "<table class ='rumour' border='1'>";
echo "<tr>";
echo "<td style = 'font-size:18pt;font-family:Noteworthy-Bold;'> Hot Rumours </td>";
echo "<tr>";
echo "<td class = 'td1'>". text2link($row['description']). "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'>". text2link($row['description']). "</td>";
echo "</tr>";
echo "</table>";
You're posting a string into mysql_fetch_assoc, and not a mysql_query...
$query = "SELECT * FROM rumour ORDER BY id DESC";
Should be
$query = mysql_query("SELECT * FROM rumour ORDER BY id DESC");
Use are directly using $query in mysql_fetch_assoc($query) which is string type.
You forget to get result. Use this instead:
$query="Your query here";
$result=msqyl_query($query);
$row = mysql_fetch_assoc($query);
You have forget to execute you query using mysql_query function
Try this code may be help you
$query = "SELECT * FROM rumour ORDER BY id DESC";
$result=mysql_query($query);
$row = mysql_fetch_assoc($result);
The manual for that function says:
array mysql_fetch_assoc ( resource $result )
You are passing it a string containing a query, not the result of running a query.
You need to pass it through mysql_query first.
… at least you do if you continue using mysql_*, which you shouldn't. It is obsolete and you should use a modern replacement.

Display only queried ID+row PHP/MySQL

I have my data stored in a MySQL table, which includes an auto_increment ID number (unique) for each new row.
I'd like users to be able to get a certain ID number, using the $_GET function.
eg. User loads http://mysite.com/id.php?id=123
Page displays ID number 123 along with the row.
echo $row['id'];
echo "<table>";
echo "<tr> <th>Unit</th> <th>Message</th> <th>Date</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['title'];
echo "</td><td>";
echo $row['description'];
echo "</td><td>";
echo $row['pubDate'];
echo "</td></tr>";
}
echo "</table>";
echo "</center>";
I'm stuck as to where I put the $_GET bit.
Thanks :)
You should append it to your query (using intval to avoid SQL injection) like this:
// use the id in your WHERE clause, convert it to an integer to avoid sql injections
$query = 'SELECT fields FROM table WHERE id = ' . intval($_GET['id']);
$result = mysql_query($query);
$row = mysql_fetch_row($result);
... do stuff with $row ...
Firstly, your code does not make much sense, since you use $row before it was defined.
Secondly, $result isn't defined at all, and it should be, for example like this:
$id = intval($_GET['id']);
$result = mysql_query("SELECT FROM table WHERE id = '$id'");
And now you know how and where to use $_GET['id'].
Dont waste your time doing the comparison afterwards, you'll save yourself alot of time by adding it to the original query
$id = intval($_GET['id']);
$query = "SELECT whatever FROM table WHERE id=$id";
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `Table` WHERE `id`='" . $id . "'";
$res = mysql_query ($query);
$exist = mysql_num_rows($res);
if ($exist) {
$row = mysqlfetch_assoc($res);
...
}

Categories