Adding user to phplist database - php

I'm trying to add a user to the phplist database. Adding the user is working, but they're not being added to the list.
$uniqueId = md5(uniqid(mt_rand(0,1000).$email));
$adduser = "INSERT INTO phplist_user_user (email, entered, confirmed, uniqid, htmlemail) VALUES ('".addslashes($email)."', 'now()', '1', '".addslashes($uniqueId)."', '1')";
$save1 = mysql_query($adduser);
It works up to this point, but then the following code doesn't:
$getid = "SELECT id FROM phplist_user_user WHERE uniqid='".addslashes($uniqueId)."'";
$userId = mysql_query($getid);
$addlist = "INSERT INTO phplist_listuser (userid,listid,entered) VALUES ('".addslashes($userId)."','2',now())";
$save2 = mysql_query($addlist);
Why is this happening?

I suppose you didn't handle properly return of $getid query.
$getId = mysql_query ("SELECT id FROM phplist_user_user WHERE uniqid='".addslashes($uniqueId)."'");
$fetchId = mysql_fetch_array($getId);
$userId = $fetchId['id'];
Now you can use $userId variable in $addlist

No need to add user in phplist_tables , simply add in mysql -> create user phplistuser;
grant all permission to this user.
Please check phplist forums for further assistance.

Related

User gets logged out, after post upload [PHP]

I got a problem with my post upload formula and need your help.
With this formula, I inserted data into 2 tables at same time and it worked perfectly fine. My next step was to insert the userid in the post table, so that the post is linked to the creator of the post.
Inserting the userid in the post table worked as well but after the upload, the user gets logged out.
Here is a part of my code
(I marked the code where I think there is something wrong with a "X")
session_start();
$db = mysqli_connect("localhost", "root", "", "abc");
if (isset($_POST['upload_post']))
{
$ad_post_title = mysqli_real_escape_string($db, $_POST['post_title']);
X $user_id = $_SESSION['id_u'];
X $_SESSION['id_u'] = mysqli_insert_id($db);
X $sql_p = "INSERT INTO ad_posts (post_title, user_id) VALUES ('$post_title','$user_id')";
if (mysqli_query($db, $sql_p))
{
$ad_post_id = mysqli_insert_id($db);
...
}
}
Maybe I have done something wrong with the session?
On the second line of your code you are overwriting a session variable of the users id, which I figure you're using to make sure the user is logged in, with the id of the newly inserted row.
$user_id = $_SESSION['id_u'];
X $_SESSION['id_u'] = mysqli_insert_id($db);
$sql_p = "INSERT INTO ad_posts (post_title, user_id) VALUES ('$post_title','$user_id')";
In the code you supplied I do not see are reason for this second line, remove it and your user won't be logged out, unless of course you're overwriting it somewhere else also.
You cannoT use mysqli_insert_id() before add data in the system.
I checked same code in my system and its working fine.
session_start();
$db = mysqli_connect("localhost", "root", "", "abc");
if (isset($_POST['upload_post']))
{
$ad_post_title = mysqli_real_escape_string($db, $_POST['post_title']);
$user_id = $_SESSION['id_u'];
$sql_p = "INSERT INTO ad_posts (post_title, user_id) VALUES ('$post_title','$user_id')";
if (mysqli_query($db, $sql_p))
{
$ad_post_id = mysqli_insert_id($db);
...
}
}

Conditional PDO Delete statement probably not working

The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.

Show username after posting (php/mysql)

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'";

php and mysqli SELECT query if it exists, then update it, else insert it

I am running a query to check my database for existing values, if they do exist then update them do not reinsert them.
Currently my code is just reinserting the values into the table instead of updating them, which means my code is never reaching the else part of my statement.
if(isset($user_info->error)){
// Something's wrong, go back
header('Location: twitter_login.php');
}
else {
// Let's find the user by its ID
$query = ("SELECT * FROM twitter WHERE oauth_provider = 'twitter' && oauth_uid = '".$user_info->id."'");
$rs=$mysql->query($query);
$results = $rs->fetch_array(MYSQLI_ASSOC);
// If not, let's add it to the database
if(empty($result)){
$query = ("INSERT INTO twitter (oauth_provider, oauth_uid, username, oauth_token, oauth_secret)
VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')");
$rs=$mysql->query($query);
$insert = ("SELECT * FROM twitter WHERE id = " . mysqli_insert_id($mysql));
$rs=$mysql->query($insert);
$results = $rs->fetch_array(MYSQLI_ASSOC);
}
else{
// Update the tokens
$update = ("UPDATE twitter SET oauth_token = '{$access_token['oauth_token']}',
oauth_secret = '{$access_token['oauth_token_secret']}'
WHERE oauth_provider = 'twitter' AND oauth_uid = {$user_info->id}");
$rs=$mysql->query($update);
$rs->close();
}
you have a typo between $result and $results
$results = $rs->fetch_array(MYSQLI_ASSOC);
// If not, let's add it to the database
if(empty($result)){
^
Here
as $result is not declared before it will always be empty and the if part will always be true.
If you want to properly prevent duplicates, create a UNIQUE KEY(oauth_provider,oauth_uid);
then use INSERT ON DUPLICATE statement to insert or update the row.
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
INSERT INTO twitter (oauth_provider, oauth_uid, username, oauth_token, oauth_secret)
VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')
ON DUPLICATE KEY UPDATE oauth_token = VALUES(oauth_token), oauth_secret = VALUES(oauth_secret)

How do I find out a specific row ID from a table?

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);

Categories