Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);
Related
I'm busy with a school project where I need to register users. I created the database and added the tables and can add users. What I just can't get right is to display the next available user id in the table.
I'm using php to retrieve the highest value but when I use echo the variable won't show. There is no error, there is no output at all, just the rest of the page.
Here is the code:
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM users" or
die(mysql_error());
$highest_id = mysqli_query($db, $query);
echo $highest_id;
?>
The code successfully connects to the database, the column is called userid, it contains int values and there are other columns as well.
All other code in the script runs perfectly, it's just this part that I can't get to work.
I have spent the last two days reading and searching for answers and I am at my wits end. Any help would be appreciated.
Thank you.
could be your table is User and not Userid
$query = "SELECT MAX(userid) AS userid FROM users"
Anyway for fetching you should use eg:
$result = mysqli_query($db, $query);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo $row[0];
The mysqli_query returns a general object that contains the results array. You have to use the mysqli_fetch_row.
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM userid" or die(mysql_error());
$highest_id_query = mysqli_query($db, $query);
var_dump($highest_id_query); // so you could check the object attributes
//loop results from query
while($row=mysqli_fetch_row($highest_id_query)){
$highest_id = $row['userid'];
echo $highest_id;
}
?>
You could also use the sql statement: SELECT COUNT(*) FROM userid
Be sure to name your tables correctly! SELECT COUNT(*) FROM users
I am working on a small community page where users will be able to post news, pictures, and comment on them. The problem where I am stuck is, whenever a user posts an entry, I want of course the username to be displayed next to the entry.
I am working with multiple tables here, one that stores the user info, and some that store the entry info (news, comments, pictures).
Now whenever a user posts something, I want to get his user ID out of the table USER, so that I can INSERT a new line INTO my table (in this case) NEWS, which wants the values Text, Title and U_ID as foreign key.
I am working with sessions, and since I had no problem simply displaying the name of the login user, I tried to use that user to select "his" row from the table and put the result into a variable ($uid) which I was hoping to use in another query for the INSERT INTO. However, according to the error message I get, something is wrong with my first query. Can anyone help?
<?php
include("dbconnect.php");
session_start();
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
$sqluser = "SELECT FROM USER USER_ID
WHERE Name = '$user'";
$userresult = $conn->query($sqluser) or die($conn->error);
while($row = $userresult->fetch_assoc()){
$uid = $row["USER_ID"];
}
} else {
header('Location: login.php');
}
if (isset($_POST["title"], $_POST["text"])) {
$title = mysqli_real_escape_string($conn, $_POST["title"]);
$text = mysqli_real_escape_string($conn, $_POST["text"]);
$sql = "INSERT INTO NEWS (Titel, Text, U_ID)
VALUES ('$title', '$text', '$uid')";
}
$conn->close();
?>
I think there is mistake in your query
$sqluser = "SELECT FROM USER USER_ID WHERE Name = '$user'";
It should be like this
$sqluser = "SELECT USER_ID FROM USER WHERE Name = '$user'";
Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['email'] . "<br />";
echo $_SESSION['username'];
}
// Close the database connection
mysql_close();
?>
I'm thankful for the help !
You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
session_start();
$_SESSION['id'] = the_id_of_your_logged_username;
}
Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";
In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.
Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"
Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);
I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup
I have a PHP login script. This is the part where the person can create a new user. My issue is I want to check if the user exists, and if the username does not exist the the table, than create the new user. However, if the user does exist, I want it to return an error in a session variable. Here is the code I have right now. This doesn't include my DB connections, but I know they do work. Its num_rows() that is being written as an error in the error_log file. Here is the code:
$username = mysql_real_escape_string($username);
$query = "SELECT * FROM users WHERE username = '$username';";
$result = mysql_query($query,$conn);
if(mysql_num_rows($result)>0) //user exists
{
header('Location: index.php');
$_SESSION['reg_error']='User already exists';
die();
}
else
{
$query = "INSERT INTO users ( username, password, salt )
VALUES ( '$username' , '$hash' , '$salt' );";
mysql_query($query);
mysql_close();
header('Location: index.php');
The error it is giving me is
mysql_num_rows(): supplied argument is not a valid MySQL result resource in [dirctory name]
mysql_num_rows()
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
Instead of doing SELECT * and then mysql_num_rows(), you can do a SELECT COUNT(*) and then retrieve the number of rows, by fetching the field (that should be 0 or 1). SELECT COUNT will always return a result (provided that the query syntax is correct of course).
Also, change the query:
$query = "SELECT * FROM users WHERE username = '$username';";
into
$query = "SELECT * FROM users WHERE username = '"
. mysql_real_escape_string($username) . "';";
Just out of curiosity, have you ever heard of upserts? I.E., "insert on duplicate key". They'd be useful to you in this situation, at least if your username column is a unique key.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$username = mysql_real_escape_string($username);
i think you have to replace the above to
$username = mysql_real_escape_string($_POST[$username]);