Ok .. I'm stuck. I tried several codes from topics here, but still not working for me so I need a little help please.
I want to log if a user is logged in for the first time and want to update that same record if the user returns. The update part works, but when my function is executed the first time, it insert a total blank record and a record with all the data provided by variables. The last_login column is NULL for the first vist and is nicely updated with the last login.
But what I can't figure out is why the first login creates these extra records.
Here is the function code I created:
function log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress)
{
global $connection;
$sql = mysqli_query($connection, "SELECT * FROM logfile_sap WHERE user_id = '{$userId}'");
if(mysqli_num_rows($sql) > 0)
{
$sql = "UPDATE logfile_sap SET last_login = NOW() WHERE user_id = '{$userId}'";
$query = mysqli_query($connection, $sql);
}
else
{
$sql = "INSERT INTO logfile_sap
(user_id, username, achternaam, district, gemeente, ipaddress, first_login)
VALUES
('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW())";
$query = mysqli_query($connection, $sql);
}
}
So as you can see I am checking if the user already exists in the logfile_sap table and if it does NOT exist I want to insert the user (which works but with an extra row) and if the user already exists the record is updated.
This is the code I use on top of the page that needs to check and adds the data in the table:
<?php log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress); ?>
I hope some has a brighter idea than me ;-)
++++++++++++++++++++++++++++++++++++++++++++
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!
Related
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'";
I have a table called user_bio, this table has one row, which was inserted manually:
id: 1
age: 30
studying: Business
language: English
relationship_status: Single
username: conor
about_me: This is conor's bio.
I have a page called account_settings_bio.php, from where the logged in user ($username) can edit their details. At the moment, when I log in as conor, I can UPDATE my data, but say for example I log in as Alice, Alice has no row in the database, therefore, I would have to INSERT data for her, but it doesn't seem to insert a new row for her.
Here is my approach:
if ($update_bio){
/*************************/
// need to check if the username has data already in the db, if so, then we update the data, otherwise we insert data.
$get_bio = mysqli_query($connect, "SELECT * FROM user_bio WHERE username ='$username'");
$row_returned = mysqli_num_rows($get_bio);
if ($row_returned == 1){
$update_details_query = mysqli_query ($connect, "UPDATE user_bio SET studying ='$new_studying', language ='$new_lang',
relationship_status = '$new_rel', about_me = '$about_me' WHERE username ='$username'");
} if ($row_returned == 0) {
$insert_query = mysqli_query ($connect, "INSERT INTO user_bio VALUES ('', '$age', '$new_lang','$new_rel', '$username', '$about_me'");
}
echo " <div class='details_updated'>
<p> Details updated successfully! </p>
</div>";
}
The UPDATE query works fine, when logged in as conor, data does change in the db, its just the INSERT which is not working.
The order of the inserted columns is not the same as in the database and there are missing some (studying).
To be sure, you could rewrite your insert SQL to be more explicit:
INSERT INTO user_bio (id, age, studying, language, relationship_status, username, about_me) VALUES (NULL, '$age', '$new_studying', '$new_lang','$new_rel', '$username', '$about_me'"
Note: why not use if($row_returned==0){ /* INSERT */ } else { /* UPDATE */ } instead of a double if?
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
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);
i am trying to add an if statement to a mysql query so that it checks the user exists from a table called ptb_users in the user_id column before the query runs.
users can write on other users walls and before a user can write on a users wall / before the query inserts into ptb_wallposts, i want it to check that the from_user_id = the ptb_users.user_id.
i am trying to do this but i get syntax errors all over my page can someone please can someone show me how i would need to structure this:
<?php
// check if the review form has been sent
if(isset($_POST['review_content']))
{
$content = $_POST['review_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['review_content']!='')
{
if exists (select user_id from ptb_users where user_id = #id)
begin
{
$sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
mysql_query($sql, $connection);
$_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Wall Post Added</strong> - Your comment was posted to {$profile[2]}'s wall.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} }
}
end
else
begin
echo "error user doesnt exist"
end
?>
Here's an example of if statement (from MySQL Reference)
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
Let me explain a little more better, i'll compare between PHP and SQL if statements
PHP:
IF(variable > 0){
anything..
}
SQL:
IF variable > 0 THEN anything..
Read more:MySQL Reference - IF STATEMENT