The UserId field does not get updated with the value passed by the application, whereas all the other fields get updated.
This is my insert query and other related code from my app:
$sql = "INSERT INTO usermaster (UserId, UserName, Password,OwnerOrEmp, DBName, DeleteFlag, CreateDate, UpdateDate) values(:id, :userName, :password, :ownerOrEmp, :dBName, :deleteFlag, :createDate, :updateDate)";
$q = $pdo->prepare($sql);
//echo $uid;
$q->bindParam(':id', $uid);
$q->bindParam(':userName', $name);
$q->bindParam(':password', $pass);
$q->bindParam(':ownerOrEmp', $ownEmp);
$q->bindParam(':dBName', $dbName);
$q->bindParam(':deleteFlag', $delFlag);
$q->bindParam(':createDate', $curr_date);
$q->bindParam(':updateDate', $curr_date);
$q->execute();
This is how I create my table:
CREATE TABLE `USER_MASTER` (`UserID` varchar(8) NOT NULL,
`Password` varchar(10) NOT NULL,
`UserName` varchar(100) CHARACTER SET utf8 NOT NULL,
`OwnerOrEmp` char(1) NOT NULL,
`DBName` varchar(100) NOT NULL,
`DeleteFlag` char(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And the result is
Related
I am trying to insert a boolean value with PDO into MySQLdatabase. If $data['age2'] is false the insertion doesn't take place but if true then it works. If I use the ->bindParam() method it works again. But if it was possible I would pass my variables in an associative array. Do you have an idea what I am doing wrong. at the bottom of the code I have inserted the code for the creation of the table (I want to insert into) as well. thanks
<?php
$host = 'localhost';
$user = 'root';
$password = '12345';
$dbName = 'pdo';
// set DSN data sorce name
$dsn = "mysql:host={$host};dbname={$dbName}";
// create pdo instance
$pdoConn = new PDO($dsn, $user, $password);
$pdoConn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$data = [
':fname' => 'Bob',
':sname' => 'Desaunois',
':age' => '18',
':age2' => true
];
$sql = 'INSERT INTO posts (title, body, author, is_published) VALUES (:fname, :sname, :age, :age2)';
$statement = $pdoConn->prepare($sql);
$statement->execute($data);
/*
SHOW CREATE TABLE posts;
'posts', 'CREATE TABLE `posts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `title` char(255) NOT NULL,\n `body` text NOT NULL,\n `author` char(255) NOT NULL,\n `is_published` tinyint(1) DEFAULT \'0\',\n `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB AUTO_INCREMENT=150 DEFAULT CHARSET=latin1'
posts, CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` char(255) NOT NULL,
`body` text NOT NULL,
`author` char(255) NOT NULL,
`is_published` tinyint(1) DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=150 DEFAULT CHARSET=latin1
*/
I am working on a php site with uses mysql as database, now my site is a social network like site where users follow each other, now if a user joins in he is following nobody so his stream remains empty so they leave the site quickly as well,i want users to be following my account account automatically when he joins in. Can you please tell me how to do it
here are the two tables
Table structure for table sn_users
CREATE TABLE IF NOT EXISTS `sn_users` (
`id` int(11) NOT NULL,
`username` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`password` varchar(225) NOT NULL,
`name` varchar(225) DEFAULT NULL,
`picture` varchar(100) NOT NULL,
`cover` varchar(100) DEFAULT NULL,
`job` varchar(225) DEFAULT NULL,
`address` varchar(225) DEFAULT NULL,
`date` int(11) NOT NULL,
`reg_id` text,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Table structure for table sn_follows
CREATE TABLE IF NOT EXISTS `sn_follows` (
`id` int(11) NOT NULL,
`from` int(11) NOT NULL,
`to` int(11) NOT NULL,
`date` int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=74 DEFAULT CHARSET=utf8;
Run the query when the user get registerd.
<?
//Register query
$con = mysqli_connect("[HOST", "[USER]", "[PASS]", "[DB]");
$query1 = "INSERT INTO sn_users
(username, email, password, name, picture, cover, job, address, date, reg_id, active)
VALUES
('$username', '$email', '$password', '$name', '$picture', '$cover', '$job', '$address', 'date', 'reg_id', 'active')";
mysqli_query($con, $query);
//Auto follow query
$query2 = "INSERT INTO sn_follows
(`id`, `from`, `to`, `date`)
VALUES
([ID], '[NEW REGISTERD ACCOUNT], '[YOUR ACCOUNT]', '[DATE]')";
mysqli_query($con, $query2);
Hints:
Make of the field id in your database an auto_increment
Make sure you put a hashed password in the database
you need to do some modifications in your script.
1) get last inserted id of new registered user
2) insert that last id in sn_follows table with your id
this may elaborate flow
after your user register insert query get last id like below
example:
$sql = "INSERT INTO sn_users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sqlfloow = "insert into sn_follows (from,to,date) values("your id",$last_id,date("Y-m-d H:i:s"))";
}
I am working on a PHP script where I am using PDO to insert data in mySQL. I am getting an error "23000",1062,"Duplicate entry 'email#email.com-username' for key 'email' but its inserting the data in database.
So here is my PHP codes:
if(isset($_POST['email'])){
$this->db = new connect();
$this->db = $this->db->dbConnect();
$this->encryption = new Encryption();
isset($_POST['timezone']) AND $_POST['timezone'] != 'null' ? date_default_timezone_set($_POST['timezone']): date_default_timezone_set('America/Chicago');
$this->email = $_POST['email'];
$this->username = $_POST['username'];
$this->password = $this->encryption->encode($_POST['password']);
$this->dTime = date("Y-m-d H:i:s");;
$this->sessionKey = $_POST['key'];
$this->country = $_POST['country'];
$this->region = $_POST['uregion'];
$this->browser = $_POST['browser'];
$this->ip = $_POST['accessFrom'];
$regMessage = array('error'=>false);
try{
$query = "INSERT INTO `users` (
id, email, uname, password, regtime, sessionkey, country, region, browser, ip
) VALUES (
(SELECT MAX(id) + 1 FROM `users` AS `maxId`), :email, :uname, :password, :regtime, :sessionkey, :country, :region, :browser, :ip
)";
$register = $this->db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
if($this->sessionKey === $_SESSION['token']){
$register->bindParam(':uname', $this->username);
$register->bindParam(':email', $this->email);
$register->bindParam(':password', $this->password);
$register->bindParam(':regtime', $this->dTime);
$register->bindParam(':sessionkey', $this->sessionKey);
$register->bindParam(':country', $this->country);
$register->bindParam(':region', $this->region);
$register->bindParam(':browser', $this->browser);
$register->bindParam(':ip', $this->ip);
$register->execute();
if($register->rowCount() > 0){
$regMessage = array('error'=>false);
}else{
$regMessage = array('error'=>true);
}
}else{
throw new PDOException ('Error');
}
}
catch(PDOException $e){
//this is where I am getting error so I am echoing pdo exception error
$regMessage = array('error'=>$e);
}
header('Content-Type: application/json');
echo json_encode($regMessage);
}else{
header('Location: /');
}
At the error, it is showing me duplicate entry of emailid + username for key email which looks like email#email.com-username
But in data base, I am getting email id only in email column and username only in username column.
So can any one tell me whats wrong in my codes?
My users table structure is
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(250) CHARACTER SET utf8 NOT NULL,
`uname` varchar(20) CHARACTER SET utf8 NOT NULL,
`password` varchar(100) CHARACTER SET utf8 NOT NULL,
`regtime` datetime NOT NULL,
`sessionkey` varchar(10) CHARACTER SET utf8 NOT NULL,
`country` varchar(25) CHARACTER SET utf8 NOT NULL,
`region` varchar(25) CHARACTER SET utf8 NOT NULL,
`browser` varchar(25) CHARACTER SET utf8 NOT NULL,
`ip` varchar(16) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`,`uname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
So can anyone tell me where and what is wrong?
Thank you for helping me.
The phrasing in the error message: 'email#email.com-username' for key 'email' directly corresponds to your unique key UNIQUE KEY 'email' ('email','uname'). With that line, you are creating a compound key, which you can think of as an invisible column in the index that is comprised of email-uname. There will not be a column added to your table with this format, and you are seeing the expected behavior that email and uname are treated separately in the table and together for the key.
If you want to test over and over again with the same email and username combo, you'll need to delete that row every time. Without doing this, the error you are seeing is exactly what I would expect to see if you are POST-ing the same data over and over again.
I want to also mention that you have (appropriately) specified that your id column is AUTO_INCREMENT, but then you are calculating the value manually. I would like to discourage you from doing this, and instead use NULL as the insert value. MySQL will use the correct key value in this column, and you will avoid the potential for key collision if you ever had two of these things executing at the same exact moment.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(250) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`uname` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(100) CHARACTER SET utf8 NOT NULL,
`regtime` datetime NOT NULL,
`sessionkey` varchar(10) CHARACTER SET utf8 NOT NULL,
`country` varchar(25) CHARACTER SET utf8 NOT NULL,
`region` varchar(25) CHARACTER SET utf8 NOT NULL,
`browser` varchar(25) CHARACTER SET utf8 NOT NULL,
`ip` varchar(16) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
this is the solution.
This is my table:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL default '',
`pass` varchar(32) NOT NULL default '',
`lang` varchar(2) default NULL,
`locale` varchar(2) default NULL,
`pic` varchar(255) default NULL,
`sex` char(1) default NULL,
`birthday` date default NULL,
`mail` varchar(64) default NULL,
`created` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mail` (`mail`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
And this is my query:
$query = "INSERT IGNORE INTO `users` (`name`, `mail`, `birthday`, `lang`, `locale`, `sex`, `pic`) VALUES ('".$name."', '".$email."', '".date_format($birthdaynew, 'Y-m-d H:i:s')."', '".substr($locale, 0, 2)."', '".substr($locale, -2, 2)."', '".$sex."', 'pic/".$uid.".jpg')";
$rows = mysql_query($query) or die("Failed: " . mysql_error());
$_SESSION['id'] = mysql_insert_id(); // I have tryed also mysql_insert_id($db_con) where $db_con is the link to db.
$_SESSION['name'] = $name;
$_SESSION['name'] contains correctly the name but $_SESSION['id'] contains 0.
Why ?
I'm going crazy!
Is there a particular reason why you are using INSERT IGNORE?
If you use INSERT IGNORE, then the row won't actually get inserted if there is a duplicate key (PRIMARY or UNIQUE), or inserting a NULL into a column with a NOT NULL constraint.
Referring to the pass column, as you have not defined anything to insert into it, and it has NOT NULL constraint.
EDIT:
Referring also to the mail column, as you have a UNIQUE constraint on it.
this is table schema:
CREATE TABLE `USERS` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(30) DEFAULT '',
`first_name` varchar(15) DEFAULT '',
`last_name` varchar(15) DEFAULT '',
`password` varchar(15) DEFAULT '',
`gender` int(1) DEFAULT '-1',
PRIMARY KEY (`id`)
)
in php:
$sql = 'INSERT INTO Users (email, first_Name, last_Name, password, gender ) VALUES ("'.$email.'", "'.$first_name.'", "'.$last_name.'", "'.$password.'", '.$gender.')';
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->execute();
//$user = $stmt->fetchObject();
echo 'last id was '.mysql_insert_id();
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
I can't figure out why mysql_insert_id() returns 0. there are no other processes running. id is set to auto increment. Insert is done and seen in db.
You are using PDO to interface with the database. Use PDO::lastInsertId() to get the last inserted id.
$stmt->execute();
echo 'last id was ' . $db->lastInsertId();
mysql_insert_id() is part of the ext/mysql extension. You cannot mix-match functions from both extensions to interface with the same connection.