Php pdo inserting firm with session data - php

I am working on an application that has different forms that a logged in user can fill out and submit. For example, an artist is able to submit their video through a form and that movie will be saved and uploaded to the database.
However, I would like when a form is submitted for it to automatically connect the userID and userEmail to the form when it is submitted so that I can easily check for either user id or email when pulling back data.
I have tried several different methods of doing this and nothing has worked so any help is much appreciated. I am also using foreign keys in my database tables but I do not understand how that works in connecting to a table.
So here is my table setup for users and for movies
Users table
CREATE TABLE IF NOT EXISTS. `users` (
`userID` int(11) NOT NULL. AUTO_INCREMENT,
`userEmail` varchar(100) NOT NULL,
`userPass` varchar(100) NOT NULL,
`userType` varchar(6) NOT NULL,
`agreement` enum('Yes', 'No') NOT NULL,
`userStatus` enum('Y','N') NOT NULL. DEFAULT 'N',
`tokenCode` varchar(100) NOT NULL,
PRIMARY KEY (`userID`),
UNIQUE KEY `userEmail` (`userEmail`)
) ENGINE= MyISAM DEFAULT. CHARSET=latin1. AUTO_INCREMENT=1 ;
Movies Table
CREATE TABLE `movies` (
`userID` int(11) NOT NULL,
`userEmail` varchar(250) NOT. NULL,
`movie_name` varchar(300) NOT NULL,
FOREIGN KEY (userID) Refrences users(userID),
FOREIGN KEY (userEmail) REFRENCES users(userEmail),
UNIQUE KEY `movie_name` (`movie_name`)
) ENGINE=MyISAM DEFAULT. CHARSET=latin1;
The Form page is here
( I tried adding the SESSION data to the POST here and tried the GET method to add SESSION data neither of which worked)
if(isset($_POST['submit']))
{
$email = trim($_POST['email']);
$movie = trim($_POST['movie']);
if($user_home->upload($email, $movie))
{
header("Location: Artist_Uploads.php?inserted");
}
else
{
header("Location: Artist_Uploads.php?failure");
}
}
<form action="Artist_Uploads.php" method="post" name="upload">
<input name="email" type="hidden" value="<?php echo. htmlentities($row['userEmail']); ?>" />
<input name="movie" type="text" />
<input name="submit" type="submit" />
</form>
Page that processes form submission
public function upload($email,$movie) { try
{
$stmt = $this->conn->prepare("INSERT INTO movies(userEmail, movie_name) VALUES(:email, :movie)");
$stmt->bindValue(":email",$email);
$stmt->bindparam(":movie",$movie);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
I have tried insert lasted() below the return true and before the return true.
Tried adding VALUES ('','$_SESSION[cuserID]','$_SESSION[userEmail]','') :movies");.
I also tried adding the _SESSION data in the bindValue or the bindCol neither of those worked either.
I also tried adding INSERT INTO movies FROM users.userID, users.userEmail but that did not work either.
So I do not know how to get it to insert the userID and userEmail without outputting it into the form then inserting it that way but that seems to dangerous and open to injection because someone could easily manipulate that info or
get the users ID and start playing with it. So any suggestions or pointers would be much appreciated. Thank you in advance.

The user ID or username whatever you use to uniquely and permanently identify each user should be stored in the session right after the user is authenticated. I say permanently because by using the email and then even setting up foreign key constraints on the email you are looking for a world of pain. Don't do that. Use something that would never be modified by the user. Typically users aren't allowed to modify their username and it would be pointless to give a user the option to modify their user id.
First you authenticate (something like this):
<?php
if ($user->authenticate($_POST['username'], $_POST['password'])) {
session_start();
$_SESSION['userid'] = $user->getUserId();
}
else {
echo "invalid password";
}
On subsequent requests, make sure you do session_start() first, and then you can just retrieve the information from the database using the value stored in the session. No need to send it in the form. In fact, sending it in the form would be a huge security risk because people could upload videos to other users' accounts.
session_start();
// Make sure user is logged in
if (!isset($_SESSION['userid'])) {
header("Location: login.php");
}
// Pull their info from the database
$stmt = $this->conn->prepare("SELECT * FROM users WHERE userid = ?");
$stmt->bindValue(1, $_SESSION['userid']);
$stmt->execute();
$user = $stmt->fetch();
Then you can execute your other queries based on the values you get in $user. Similar to what I mentioned earlier, get rid of emails from tables where it is irrelevant. You are duplicating information across tables and modifying the value would be very difficult. You also want to add some sort of unique way to identify the movies as well:
CREATE TABLE `movies` (
`movieID` int(11) NOT NULL. AUTO_INCREMENT,
`userID` int(11) NOT NULL,
`movie_name` varchar(300) NOT NULL,
FOREIGN KEY (userID) Refrences users(userID),
UNIQUE KEY `movie_name` (`movie_name`)
) ENGINE=MyISAM DEFAULT. CHARSET=latin1;
Then query:
public function upload($userid,$movie) {
try
{
$stmt = $this->conn->prepare("INSERT INTO movies(userID, movie_name)
VALUES(:userid, :movie)");
$stmt->bindValue(":userid",$userid);
$stmt->bindparam(":movie",$movie);
$stmt->execute();
return true;
}
catch(PDOException $e) {
echo $e->getMessage();
return false;
}
}

There are several issues going on here. I can't say I completely understand the errors you're seeing (please post any error messages as part of the question).
However, I do see a potentially significant issue with your table schema. If the movies table has users.userID as a foreign key, it should not need a userEmail attribute at all (nor its associated foreign key), as this information is obtained by joining users and movies on userID. In addition, trying to build a foreign key on userEmail is extra problematic, as users.userEmail is not guaranteed to be unique.

Answer:
On the page that process the form do the following
If (isset ($_POST ['submit']))
{
$email = $_SESSION ['userEmail'];
Everything else is normal and it works perfectly. Just make sure you have sessions setup or it will not work.

Related

How to avoid duplicate content stored in MySQL database submitted by user

I am creating a site that lets users list up to 5 companies they are associated with. When other users search these companies, all users associated with that company will show up in the search results.
The companies will be submitted by the users through a text input field.
How do I avoid users submitting duplicate companies? E.g. if UserA submits a company called stackoverflow, then UserB comes and also submits stackoverflow, there will be 2 stackoverflows in my database.
I have 3 tables:
Users Table
id|username|email
Company Table
id|company name
UsersCompany Table
id|userID|companyID
I'm using Laravel 5
You should really use Laravel Validation and keyword unique to handle this:
$this->validate($request, [
'company' => 'required|unique:company|max:255'
]);
Also, you could use custom Request class to handle form validation:
public function rules()
{
return [
'company' => 'required|unique|max:255'
];
}
If I were you, I'd use second one.
You can do it with a simple check. If the company does not exists create a new Company or attach the Company to the user.
I assume the companies are submitted in one single text input seperated by commas and you have setup your relations correct. If not check this.
Example:
// Inside your controller
public function post_something(Request $request)
{
// Always good to validate
$this->validate(....);
// Somehow get your user model
$user = ....
// Get companies input and loop
$company_names = $request->input('company_names');
$company_names = explode(',', $company_names );
foreach ($company_names as $company_name)
{
$company = Company::firstOrCreate(['company_name' => $company_name]);
$user->companies()->attach($company);
}
// Your other stuff
//
....
}
This can achieve this by
either creating PRIMARY Key or UNIQUE on company_Name
ALTER TABLE company_Table ADD PRIMARY KEY(company_Name)
ALTER TABLE company_Table ADD UNIQUE (company_Name)
or
IF NOT EXISTS(QUERY) Then INSERT
or
Create BEFORE INSERT trigger .
http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
You can add a unique index on the table. So if your column is named company_name and table is companies you could execute the following:
alter table companies add unique (company_name)
Or alternatively you can do a query in programming before you allow an insert, which checks if the entry already exists. Or a combination of both..
you can use unique key for companies table
http://dev.mysql.com/doc/refman/5.7/en/constraint-primary-key.html
This is very easily obtainable, by using UNIQUE in MySQL.
ALTER TABLE `company_Table` ADD UNIQUE (
`company_Name`
)
By putting this into MySQL, the company_Name column becomes UNIQUE, meaning there can only be one. If you attempt to insert another one, an error returns.
UNIQUE can also be used on member emails on a userbase, if you don't want somebody to log in with the same email. UNIQUE is also perfect for POST_IDs, MEMBER_IDs, COMMENT_IDs, and several others, that could become very useful on a blog, forum, or social media site.
If you would like to create the UNIQUE key upon creating this table, here is how you would do so:
CREATE TABLE Company_Table
(
ID int NOT NULL,
Company_Name varchar(255),
UNIQUE (Company_Name)
)
W3schools has a good tutorial on this: Here
On my opinion you should use Eloquent firstOrCreate method
If you will use this approach, then you even no need any "unique" validation under the companies.
Lets start
DB Schema
users
id
username
companies
id
company_name
user_company
id
user_id
company_id
Models (only relations methods)
User.php
public function companies()
{
return $this->belongsToMany('NAMESPACE_TO_YOUR_MODEL\Company');
/*you can set foreign keys fields if it's not canonical see docs*/
}
Company.php
public function users()
{
return $this->belongsToMany('NAMESPACE_TO_YOUR_MODEL\User');
}
Controller
public function store(CompanyRequest $request)
{
$companiesFromRequest = $request->get('companies');
// it's just for example, you can retreive companies from request with any other approach
$companiesId = [];
foreach ($companiesFromRequest as $company) {
// assumes that $company variable contains all or at least part of info,
// that need to create or identify particuliar comapny
$c = Company::firstOrCreate($company);
$companiesId[] = $c->id;
}
// in this case we just retreive existing user
$user = User::findOrFail($request->get('user_id'));
$user->companies()->sync($companiesId);
// or you can use
// $user->companies()->attach($companiesId);
// difference between this commands you can found in official laravel docs
return redirect('any/place/you/wish')
}
Application Layer:
Use Laravel's Validation property 'unique' to establish that only unique company name is allowed.
public function store(Request $request)
{
$this->validate($request, [
'company_name' => 'required|unique:companies|max:255',
]);
// The company name is valid, store in database...
}
Database Layer:
add a constraint as unique to the migration of the company's table for company_name column.
$table->string('company_name')->unique();
found the answer in larval i just use firstOrNew() Creation Method
will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:
as stated here
Try to build schema as following to get optimum performance.This structure helps you to avoid duplicate data and also do code validations in Laravel to avoid malicious inputs.
CREATE TABLE IF NOT EXISTS `Users Table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `Company Table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`company name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `company name` (`company name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `Users Company Table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userID` int(11) unsigned NOT NULL,
`companyID` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `userID` (`userID`),
KEY `companyID` (`companyID`),
CONSTRAINT `Users Company Table_ibfk_1` FOREIGN KEY (`userID`) REFERENCES `Users Table` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Users Company Table_ibfk_2` FOREIGN KEY (`companyID`) REFERENCES `Company Table` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
I hope this code helps you. This is a sql code to insert unique data
INSERT INTO UsersCompanyTable (userID, companyID)
SELECT * FROM (SELECT $_POST("user_id"), $_POST("company_id")) AS tmp
WHERE NOT EXISTS (
SELECT companyID FROM UsersCompanyTable WHERE companyID = $_POST("company_id")
) LIMIT 1;
You should allow user to select company, and then simply give reference of UserID, CompanyID tables in UsersCompany Table. So you will always have a unique record if UserA insert StackOverFlow and UserB also insert StackOverFlow, in your database. It will be like:
1-UserA-StackOverflow
2-UserB-StackOverFlow.
Or, if you want user to enter the company, check if the same company exists or not:
var checkcompany= "select * from Company Table where company name=company name"
Than check
if(checkcompany ! =null)
Than insert the record or else ignore it.

Foreign Key Failure in MySQL

I have created a database composed of three tables. This is my query in creating my tables with Foreign Key.
CREATE TABLE reporter
(
reporterid INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(1000) NOT NULL,
lastname VARCHAR(100) NOT NULL,
PRIMARY KEY (reporterid)
);
CREATE TABLE flood
(
floodid INT NOT NULL AUTO_INCREMENT,
address VARCHAR(500) NOT NULL,
description VARCHAR(1000) NOT NULL,
dateofflood DATE NOT NULL,
timeofflood INT NOT NULL,
PRIMARY KEY (floodid)
);
CREATE TABLE reports
(
reportid INT NOT NULL AUTO_INCREMENT,
timereport NODATATYPE NOT NULL,
datereport DATE NOT NULL,
rid INT NOT NULL,
fid INT NOT NULL,
PRIMARY KEY (reportid),
FOREIGN KEY (rid) REFERENCES reporter(reporterid),
FOREIGN KEY (fid) REFERENCES flood(floodid)
);
I created a system in order for me to add records/row on my database through PHP. This is my code:
<?php
mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("flooddatabase")or die("Connection Failed");
$description = $_POST['description'];
$address = $_POST['address']; // Make sure to clean the
$dateofflood=$_POST['dateofflood'];
$timeofflood=$_POST['timeofflood'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$dateofreport=$_POST['dateofreport'];
$timeofreport=$_POST['timeofreport'];
$query = "INSERT into flood(address,description,dateofflood,timeofflood) values ('$address','$description','$dateofflood','$timeofflood')";
$query2 = "INSERT into reporter(firstname,lastname) values ('$firstname','$lastname')";
$query3 = "INSERT into reports(dateofreport,timeofreport) values ('$dateofreport','$timeofreport')";
if(mysql_query($query))
if(mysql_query($query2))
if(mysql_query($query3))
{
echo "";
} else
{
echo "fail";
}
?>
The result that I am getting is fine. It's just that, in my REPORTS table, there is no foreign key that is being generated. For example I input something on my reporter table and flood table, the foreign key 'rid' and 'fid' has no values that references to both tables. Need help thank you.
Get the just inserted Primary key value from flood table insert
query. And store it to a variable say $f_id;
Get the just inserted primary key value from reporter table insert
query and store it to a variable say $r_id;
Now Make your last insert statement like below:
"INSERT into reports(dateofreport,timeofreport,rid,fid) values ('$dateofreport','$timeofreport',$r_id,$f_id)";
I am not giving you a direct copy paste solution.
If you need to know how to get the last inserted id by executing an insert query then look at this link
there is no foreign key that is being generated
I'm not entirely sure what you even mean by that. Foreign keys aren't "generated". Primary keys can be, which you do:
reporterid INT NOT NULL AUTO_INCREMENT
(as well as for your other two tables)
the foreign key 'rid' and 'fid' has no values
Well, look at your query:
INSERT into reports(dateofreport,timeofreport) values ...
Where do you insert values for rid and fid? I'm actually pretty surprised this query works at all, since those columns don't allow NULL values:
rid INT NOT NULL,
fid INT NOT NULL,
(Though your column names also don't line up, so I find it likely that the code you're showing isn't actually the code you're using...) That point aside however, the fact still remains that if you want a value in those fields then you have to put a value in those fields:
INSERT into reports(dateofreport,timeofreport,rid,fid) values ...
After each query, you can get the last generated identifier from mysql_insert_id():
$last_id = mysql_insert_id();
Use that to then populate the values being inserted as foreign keys in subsequent queries.
Also worth noting, the mysql_* libraries are long since deprecated and have been replaced with mysqli_ and other libraries such as PDO. I highly recommend you upgrade to a current technology, since what you're using isn't supported by any vendor.
Additionally, and this is very important, your code is wide open to SQL injection attacks. This basically means that you execute any code your users send you. You should treat user input as values, not as executable code. This is a good place to start reading on the subject, as is this.

How to store each individual IP adderss from $_SERVER['REMOTE_ADDR'] to a MySQL database?

I need to get a list of IP addresses of all connecting visitors to my website. I know I can get an ip address by using $_SERVER['REMOTE_ADDR'] but it always shows me only my IP address, if someone another connects to the website, it shows only their ip address to them. So I decided to make a database where I will store each individual value, but I dont know how to loop through to get all individual ip address. I am a bit confused.
Consider this script which you already have..
<?php
echo $_SERVER['REMOTE_ADDR'];
Assume... When you put this script on your site say http://yourwebsite.com/ip.php , When you access it .. it prints some 129.X.X.X (which is your IP) , when somebody accesses it , It will show their IP say .. 80.X.X.X
To write it to a file.. You could do this..
<?php
file_put_contents('visitorsip.txt',echo $_SERVER['REMOTE_ADDR'],FILE_APPEND);
To insert into a database.. You can write a query like
<?php
$ip = $_SERVER['REMOTE_ADDR'];
//do all your db connections..
$sql = 'INSERT INTO iptable (name) VALUES (?)';
$sth = $dbh->prepare($sql);
$sth->execute(array($ip));
$dbh->commit();
Looping through...
<?php
$sth = $dbh->prepare("SELECT name FROM iptable");
$sth->execute();
$result = $sth->fetchAll(); //This $result array holds all your IP Addresses
//Lets loop..
foreach($result as $ips)
{
echo $ips."<br>";
}
Make a table to keep ip's and counts. Might want to include a isSpider and which spider. Something like this:
CREATE TABLE `ip_counts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip` varchar(255) CHARACTER SET utf8 NOT NULL,
`count` int(11) NOT NULL,
`isSpider` tinyint(4) NOT NULL,
`spider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ip` (`ip`)
) ENGINE=InnoDB
And for each visitor insert:
INSERT INTO ip_counts SET ip='".$ip."', count=1, isSpider=".$isSpider.", spider='".$spider."' ON DUPLICATE KEY UPDATE count=count+1
IP of login user can be fetched from:
httpcontext.Request.UserHostAddress

update then replace dies

If there is a row for user_id then I want to update, if not insert (but I was told to use replace). In the table there is id (which is primary key, auto inc) and user_id (index, session relates to). I have a form that when the data is changed it should be changed in the database for that particular user in session, otherwise it is just added for that particular user in session
if (empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$query="UPDATE thesis SET thesis_Name ='$thesis_Name',
abstract='$abstract' WHERE id='$_SESSION[user_id]'
IF ROW_COUNT()=0
REPLACE INTO thesis (thesis_Name,abstract)VALUES ('$thesis_Name', '$abstract')
";
mysql_query($query) or die();
// query is ok?
if (mysql_query($the_query, $link) ){
// redirect to user profile
header('Location: myaccount.php?id=' . $user_id);
}
With this the page just dies.
EDIT:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
Thanks so much
You don't need to do the UPDATE first - REPLACE handles all of this for you. From the MySQL manual:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.
Therefore, so long as id is a unique key in your thesis table, the only SQL you need is:
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('$_SESSION[userid]', '$thesis_name', '$abstract');
There are a few things in your code that pose problem. First you don't have to do an insert and a replace in the same query : replace will insert if there is no row to replace (besides, I'm not even sure the sql syntax you're using is correct)...
Then you do a mysql_query($query) or die() which is probably where your code dies (maybe due to the fact that the sql syntax you used could be incorrect).
Right after that, you do a mysql_query again, which would reexecute the query a second time. Anyway, if your query didn't work, your code would have died on the previous line...
What you could do would be
$query = "REPLACE INTO blablabla";
if (!mysql_query($query))
echo "the query failed";
else header ("location:blabla");
but your query should mention for which user_id you want to update like this
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('{$_SESSION[userid]}', '$thesis_name', '$abstract');
INSERT
INTO thesis (id, abstract, thesis)
VALUES ('$_SESSION[user_id]', '$abstract', '$thesis_Name')
ON DUPLICATE KEY
UPDATE
abstract = VALUES(abstract),
thesis_Name = VALUES(thesis_Name)
You can do it with prepared statements.You can see an example sql ;
DROP PROCEDURE IF EXISTS `UPDATETHESIS`
|
CREATE PROCEDURE `UPDATETHESIS` (IN _id VARCHAR(50), IN _thesis_name VARCHAR(50), IN _abstract VARCHAR(50))
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY INVOKER
IF EXISTS (SELECT * FROM thesis WHERE id = _id)
BEGIN
UPDATE thesis SET thesis_Name = _thesis_name,
abstract = _abstract WHERE id = _id
END
ELSE
BEGIN
INSERT INTO thesis (thesis_Name,abstract) VALUES (_thesis_name, _abstract)
END
You can call this like CALL UPDATETHESIS(userid, thesis_name, abstratc);

OOP PHP user class (usercake) not adding to database

I recently found this little user class script called usercake (http://usercake.com/), has all the basic functionality and seems to work very well.
My problem: The first user gets added to the database fine, but after that it is not working. Clearly there's just something slightly wrong that I'm not figuring out ( i do not know oop php very well). No errors occure (that i can see), and the email gets sent out.
I've installed it multiple places with the same fate. I'd like to fix it because using this script saves a lot of reinventing the wheel time.
Here is the URL where I have it: http://rawcomposition.com/birding/loggedin/register.php
Here is the function that gets called once everything is validated:
public function userCakeAddUser()
{
global $db,$emailActivation,$websiteUrl,$db_table_prefix;
//Prevent this function being called if there were construction errors
if($this->status)
{
//Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
//Construct a unique activation token
$this->activation_token = generateActivationToken();
//Do we need to send out an activation email?
if($emailActivation)
{
//User must activate their account first
$this->user_active = 0;
$mail = new userCakeMail();
//Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE",array($websiteUrl,$this->activation_token));
//Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array("#ACTIVATION-MESSAGE","#ACTIVATION-KEY","#USERNAME#"),
"subjectStrs" => array($activation_message,$this->activation_token,$this->unclean_username)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if(!$mail->newTemplateMsg("new-registration.txt",$hooks))
{
$this->mail_failure = true;
}
else
{
//Send the mail. Specify users email here and subject.
//SendMail can have a third parementer for message if you do not wish to build a template.
if(!$mail->sendMail($this->clean_email,"New User"))
{
$this->mail_failure = true;
}
}
}
else
{
//Instant account activation
$this->user_active = 1;
}
if(!$this->mail_failure)
{
//Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `".$db_table_prefix."Users` (
`Username`,
`Username_Clean`,
`Password`,
`Email`,
`ActivationToken`,
`LastActivationRequest`,
`LostPasswordRequest`,
`Active`,
`Group_ID`,
`SignUpDate`,
`LastSignIn`
)
VALUES (
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0',
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
return $db->sql_query($sql);
}
}
}
And here is the table structure:
CREATE TABLE IF NOT EXISTS `userCake_Users` (
`User_ID` int(11) NOT NULL AUTO_INCREMENT,
`Username` varchar(150) NOT NULL,
`Name` varchar(100) NOT NULL,
`Username_Clean` varchar(150) NOT NULL,
`Password` varchar(225) NOT NULL,
`Email` varchar(150) NOT NULL,
`ActivationToken` varchar(225) NOT NULL,
`LastActivationRequest` int(11) NOT NULL,
`LostPasswordRequest` int(1) NOT NULL DEFAULT '0',
`Active` int(1) NOT NULL,
`Group_ID` int(11) NOT NULL,
`SignUpDate` int(11) NOT NULL,
`LastSignIn` int(11) NOT NULL,
PRIMARY KEY (`User_ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
To me, there are 2 possibilities why it is not adding further users after the first one is added:
First, $this->mail_failure flag is set to TRUE for the following user accounts after the first user is created. But this scenario is not likely because it is the same code that has run successfully for the first user and therefore there is no reason why the flag should be TRUE for others.
Second possibility is that $this->status is FALSE for the second user account. If false, the method userCakeAddUser() does not do anything. The reasons why this flag could be false is either the username or the email address already exists.
Are you using the same username or email address you used for the first account for the second account as well? I'm sure you must not be using the same username but perhaps the same email address. The usercake classes does not allow the same username or same email addresses.
Hope this helps.
I would do 4 things with this uggly code :
1) to enable the error_reporting mode so that you can see something in case sthg occurs :
error_reporting(E_ALL);
2) to test this INSERT sql straight into the dB to make sure it's working properly, and validate this piece of code. If the sql INSERT request is valid, then check the access conditions to these SQL request, like Abhay said above,
3) As we do not have your all config available, a guess game is difficult. So I'd suggest you to add one NULL field for the AI User_ID.
$sql = "INSERT INTO `".$db_table_prefix."Users` (
`User_ID`, // Add this here
`Username`,
`Username_Clean`,
`Password`,
`Email`,
`ActivationToken`,
`LastActivationRequest`,
`LostPasswordRequest`,
`Active`,
`Group_ID`,
`SignUpDate`,
`LastSignIn`
)
VALUES (
NULL, // and that one
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0', // later, I would also try using an int for an int
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
4) to find another one, better coded, using OOP and PDO.
You given Name as NOT NULL and in Insert statement of your code is not sending Name value, so mysql will throw an exception, saying Name cannot be null, check this once.

Categories