I have a MySQL database on my domain, than I made a table called AccountInformation. In that table are things like AccountID, AccountName, FirstName, SecondName etc.
I made a PHP program which connects to that database and is able to fetch all rows and display them, but thats not what I want it to do. I want to fetch information from a certain row depending on its ID.
Pseudo-Example :
$UserName String
$SearchID = 1
$UserName = fetchrow where 'AccountID' = $SearchID and get 'AccountName' of that row
So that I now have the UserName of the account with the ID 1 in $UserName.
OK, this should be what you're looking for...
/* put the value of $number to the id number you want to get other info from*/
$number = "1";
$sql = mysql_query("select * from `AccountInformation` where `id`='$number';");
$result = mysql_fetch_assoc($sql);
echo $result["AccountName"];
Related
Right, so I have a quite weird and complex question (you would've even noticed from the title of this question). I have two databases: "admin" and "users". In the "admin" database I have a table called "user_accounts" where one of the column's name is "course", this is what it looks like:
In the "users" database, I have 2 tables called "booked courses" and "user_accounts", where the columns I need are "email", "user" and "course_name", this is what it looks like:
So, what I'm really trying to do is take the value of "course" column from the "user_accounts" table, check if it matches the records in the "course_name" column in the "booked_courses" table. If it does match ("business basics" in this case), then check what are the values of the "user" column in "booked_courses" table (copy both of the emails in this case) and then match those records with the "email" column in the "user_accounts" table (this time check it in the "users" database.
This is the code I have tried:
<?php
// Include the connection for the admin database
include_once 'handlers/db_conn_admin.php';
// Select and fetch the information from user_accounts table in the admin database
$sql = $conn->prepare("SELECT * FROM user_accounts WHERE username = ?");
$sql->bind_param("s", $username);
$username = $_SESSION['username'];
$sql->execute();
$result = $sql->get_result();
$trainer = mysqli_fetch_assoc($result);
// Now include the connection for the users database
include_once 'handlers/db_conn_users.php';
// Select and fetch the information from booked_courses table in the users database where the course_name is whatever is the value of "course" column in user_accounts table in the admin database
$sql_booked_courses = $conn->prepare("SELECT * FROM booked_courses WHERE course_name=?");
$sql_booked_courses->bind_param("s", $course_name);
$course_name = $trainer['course'];
$sql_booked_courses->execute();
$result_booked_courses = $sql_booked_courses->get_result();
$email = mysqli_fetch_assoc($result_booked_courses);
// Now select and fetch the information from user_accounts table in the users database where the email is whatever is the value of "user" column in booked_courses table in the users database
$sql_user_accounts = $conn->prepare("SELECT * FROM user_accounts WHERE email=?");
$sql_user_accounts->bind_param("s", $user);
$user = $email['user'];
$sql_user_accounts->execute();
$result_user_accounts = $sql_user_accounts->get_result();
// And now for the end make the loop to display all the information about the users of the selected email addresses (in this case "email#example.com" and "email2#example.com")
while($user_info = $result_user_accounts->fetch_assoc()) {
?>
<h1><?php echo $user_info['email'] ?></h1>
<?php
}
?>
Right so, this actually does work, however at the end I'm only getting a single (oldest) result from the "user_accounts" table from the "users" database, when I need to get all the email addresses and display them on the HTML page. As i'm guessing since the "mysqli_fetch_assoc" function only gives you one value normally, I need to use the loop. The problem starts when I have 2 different email addresses with the same course column value. I'm not very sure how to make a loop into a loop or how to save the fetched results (in this case 2 email addresses) without a loop so that then I can display the info of the both rows, and I can't seem to find any solutions for this type of a situation.
I exactly know this probably sounds super confusing, complex and unnecessary, however I've built the whole system on these tables and this is the little feature I'm adding and I don't have much of a choice to combine tables or anything like that. Please someone help me out on this if you have any solutions, and let me know for any additional information you might need in the comments.
So what I actually did was I used while loop inside a while loop not to lose any of the fetched results from the database:
// EVERYTHING STAYS THE SAME ABOVE THIS CODE
$sql_booked_courses = $conn->prepare("SELECT * FROM booked_courses WHERE course_name=?");
$sql_booked_courses->bind_param("s", $course_name);
$course_name = $trainer['course'];
$sql_booked_courses->execute();
$result_booked_courses = $sql_booked_courses->get_result();
// I ADDED THIS CODE:
while($emails = $result_booked_courses->fetch_assoc()) {
$email = $emails['user'];
// Now select and fetch the information from user_accounts table in the users database where the email is whatever is the value of "user" column in booked_courses table in the users database
$sql_user_accounts = $conn->prepare("SELECT * FROM user_accounts WHERE email=?");
$sql_user_accounts->bind_param("s", $user);
$user = $email['user'];
$sql_user_accounts->execute();
$result_user_accounts = $sql_user_accounts->get_result();
// And now for the end make the loop to display all the information about the users of the selected email addresses (in this case "email#example.com" and "email2#example.com")
while($user_info = $result_user_accounts->fetch_assoc()) {
?>
<h1><?php echo $user_info['email'] ?></h1>
<?php
} } // AND CLOSED THAT LOOP HERE (SO THERE IS A LOOP INSIDE A LOOP THAT WORKED
?>
I'm not sure how convenient that is but it works perfectly fine.
Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id
Suppose I have a database table consisting of three columns - Userid, Username & Password. And let's assume I am building a Log-in Form and the password is stored in encrypted form. So, before it can be compared with the original password, it needs to be processed a little.
So, I let the user enter the username and password in the form.
include('db.php');
$getuid = $connection->prepare('SELECT FROM users WHERE username = :u');
$getuid->execute(array("u" => $_REQUEST['username']));
Now, I have executed the statement, and the row with the Entered Username is selected.
What I Want to Do ?
After Selecting the Row, I want the corresponding Password(which is in encrypted form) and Userid to be stored in $pass, $userid variables. How can I do that?
the select query needs to be $getuid = $connection->prepare('SELECT * FROM users WHERE username = :u'); where * selects/gets all columns from the table users.
Then traverse the results, as per their column names (username, and say pwd) to get their corresponding values, as shown below:
$results = $stmt->fetch(PDO::FETCH_ASSOC);
foreach ( $results as $v) {
$username = $v['username'];
$pwd = $v['pwd'];
}
Note: you cannot retrieve the original or decoded password, its explained nicely here
If user enters a username as uname,then use this query to get
select password,userid from users where user_name=uname
I am having trouble with a function that checks if a set of user entered info (username and password) exists within either of the two possible tables where this information is stored.
The first table is the users table. It contains the first set of specific user information.
The last table is the listings table. It contains the second set of specific user information.
I have basically modified my original code to include the new listings table, and hence the trouble coming from within that task. The old code basically counted the number of results in the users table, if the result was greater than 0, then the function returned true, else false.
Now I have been stuck on the best way to go about adding another table to the query, and function. So I have been playing around with a union.
This was the original query:
SELECT COUNT(*) FROM users
WHERE id='$accNum' AND password='$password'
This returned a count of either 0 or 1 based on the info stored in the users table.
This is how I have reworked the query to include a count of the additional listings table:
SELECT count . *
FROM (
SELECT COUNT( * )
FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (
SELECT COUNT( * )
FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password'
)
)count
This returned a result set of two rows, the first relating to the users table, and the second relating to the listings table. Then a column called COUNT (*) that contained the result count. This is the result set that I see within php myadmin.
Now this is the function:
function databaseContainsUser($accNum, $password)
{
include $_SERVER['DOCUMENT_ROOT'] . '/../../includes/db.inc.php';
$accNum = mysqli_real_escape_string($link, $accNum);
$password = mysqli_real_escape_string($link, $password);
$sql = "SELECT count . *
FROM (
SELECT COUNT( * )
FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (
SELECT COUNT( * )
FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password'
)
)count
";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for user.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The problem that I have, is trying to work out how exactly to check the results to ascertain if the given log in credentials are valid.
I tried this: if (($row[0] > 0) || ($row[0] > 0)) But a var dump on $row showed that only the first row (count of users table) was being added to the array.
So I decided that this was complicated, and a long way to the final result.
So I tried selecting only the id column of the result as in:
...
`COUNT( * )` to `id`
...
$data = mysql_query($sql);
$num_sql = mysql_num_rows($data);
if ($num_sql > 0)
...
But this did not work out for me either.
But in either instance, my hours of trial and error have provided me with no success... So I've decided to seek help from the knowledgeable members of Stack Overflow!
So my question is this, what would be a logical way of going about this task? I am looking for any suggestions, or positive input what so ever here.
As I am fairly new to dabbling with PHP and mysql, if you would like to provide some code to explain your suggestions or input on the matter, it would more than likely help me to better understand the answer.
If you are checking existence only try doing this that way:
select case when
exists (SELECT 1 FROM users WHERE id = '$accNum' AND PASSWORD = '$password') or
exists (SELECT 1 FROM listings WHERE id = '$accNum' AND PASSWORD = '$password')
then 1 else 0
end as itDoesExist
It returns always one row with one column with 1 when record exists in at last one table (else 0).
Do not use count to check whether some specific record/-s exist/-s in table, it's usually slower than simple exists.
Looks like you're going to get two rows in the result no matter what. Try this:
$sql = "SELECT id,password
FROM users
WHERE id = '$accNum' AND password = '$password'
UNION
SELECT id,password
FROM listings
WHERE id = '$accNum' AND password = '$password'
";
Now you can just check mysql_num_rows() to see if there's a match in either of the tables.
There are a couple of ways to go about this; if we are to stick with the approach you started with; you can simplify the query to:
$sql = "SELECT COUNT(1) FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (SELECT COUNT(1) FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password')";
The reason you are only seeing one result, is because thats the way mysql_fetch_array() works, try doing this to get all results:
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
var_dump($data);
Now you should have both values in there to validate with your conditional statements.
i am fairly new to php. I am trying to print out the username and age based on the user session login, and cant seem to figure it out.
I have two separate table, one for login and another that contains the users info.
user table id-> 1 | logon -> shawn#aol.com | passwrd -> somthing
usersinfo id-> 1 | logon ->shawn#aol.com | username -> mathewkng1 | age -> 23
i can print out the session login using $_SESSION['logon'], this will give shawn#aol.com
what i want to do is instead of printing out shawn#aol.com i want to print out mathewkng1, age 23.
i tried,
SELECT users.*, usersinfo.* FROM users, userinfo WHERE users.logon = userinfo.logon
$logon = session_start();
if($_SESSION['logon']){
while($rows = mysql_fetch_array($user )){
$username = $rows['username '];
$age= $rows['age'];
}
echo " .$username." <br> ".$age." ";
}
i get the following error $username and $age not defined.
First advice is not to relay on the logon as a key for the second table. Rather use a field id_user instead of logon an id in the userinfo table.
then you can change also the select to
Select * from users join userinfo on users.id = userinfo.id_users
then you have an typo in
$username = $rows['username '];
i don't see where you do $_SESSION['logon'] and what you add there but i guess that it is an ID of that users table, so you should add that to the select up there.
$username = $rows['username '];
There is a space within the string behind username. I guess that shouldn't be there. Also, I cannot see if these tables contain an age. If $username is not defined, it might be because there is no record returned. Assumingly there is an error in your query (could by a Duplicate Fieldname error because both returned tables will contain the same logon field), but there could also be an error in the way you execute the query.
Please try these suggestions and check for the result of mysql_query and mysql_fetch_* to see if an error occurred. If mysql_query returns false (check using the === operator), get the result of mysql_error() to see what the exact error is.
Post that error and a little more code if you need more help.
Looking at your table structure, you don't need the join.
This sould be sufficient:
SELECT * from usersinfo where logon = 'shawn#aol.com'
session_start();
if($_SESSION['logon'])
{
$query = "SELECT * FROM usersinfo WHERE logon=" . $_SESSION['logon']
$res = mysql_query($user, $sqlConnection)
while($row = mysql_fetch_array($res))
{
$username = $row['username'];
$age= $row['age'];
}
echo $username ." <br /> ".$age;
}