I need some quick help, I need to know if I can somehow increment the $user_id by one so that I do not get a duplicate entry error. Do I just add a +1 after ['user_id']?
public function insert_video($video_id,$user_id,$caption) {
$userObject = array();
$userObject['user_id'] = $user_id;
$userObject['video_id'] = $video_id;
$userObject['caption'] = str_replace(array("'",'"'), '', $caption);
$userObject['description'] = '';
$userObject['votes'] = 0;
$userObject['upload_time'] = date('Y-m-d H:i:s');
$userObject['version'] = $this->contests->contest->version; //4
//if($this->contests->contest->auto_approve)
$userObject['approved'] = 1;
$this->db->insert('photos', $userObject);
return $this->db->insert_id();
ok guys I edited the function and removed any mention of user_id but for some reason I still get the error when I try to submit another video. Should I try dropping that column on the table? here is my updated function
public function insert_video($video_id,$caption) {
$userObject = array();
//$userObject['user_id'] = $user_id+1;
$userObject['video_id'] = $video_id;
$userObject['caption'] = str_replace(array("'",'"'), '', $caption);
$userObject['description'] = '';
$userObject['votes'] = 0;
$userObject['upload_time'] = date('Y-m-d H:i:s');
$userObject['version'] = $this->contests->contest->version; //4
//if($this->contests->contest->auto_approve)
$userObject['approved'] = 1;
$this->db->insert('photos', $userObject);
return $this->db->insert_id();
}
You need to set up your user_id To auto increment. If you find it easier as you clearly have a table already set up, use phpMyAdmin to set the AI tick box to true.
Then when you INSERT, you'll get a unique value. You do not need to specify the user_id as that'll be taken care of.
INSERT INTO users (FirstName,LastName) VALUES ('Matt','HB')
I suppose you need to have 2 tables, one that holds a user info with auto incresment column e.g. "ID".
In table photos don't use auto incresment for user_id, as you need to give users ability to insert multiple photos and update current. just change in your table:
`user_id` to `ID` -> this will auto incresment
create new column `user_id` int 200.. this will be a reference of `column - "ID"` from **userinfo** table;
//then run your query:
INSERT INTO photos (user_id, video_id, caption, description, votes, upload_time, version, approved) VALUES (7339, 'fDTm1IzQf-U', 'new test', '', 0, '2014-11-12 16:17:36', '19', 1)
Related
I have table with favorites programm. I will add with ajax query to database favorite programm id's to table with user id. How I can skip a duplicate programm id with current user id.
I now create this method for skip duplicate values but not working in calling:
public function test($programm_id){
$fav = new \App\Favorite;
$user_id = Auth::id();
$fav_count = $fav::where('id_user', Auth::user()->id)->count();
$getFavorites = $fav::where('id_user', $user_id)->get()->toArray();
$userProgramms = $fav->where('id_user', $user_id)->select('id_program')->get()->toArray();
$bool = true;
foreach ($userProgramms as $array) {
foreach ($array as $value) {
if($value === $programm_id) $bool = false;
}
}
if($fav_count <= 5){
if ($bool){
$fav->id_user = Auth::user()->id;
$fav->id_program = $programm_id;
$fav->save();
}
}
}
Here my table:
Please see my method favorite() in this controller: Controller
My updated code can't more 1 saves to database.
$fav = new \App\Favorite;
$fav_count = $fav::where('id_user', Auth::user()->id)->count();
if($fav_count <= 5)
{
$fav->updateOrInsert(['id_user' => Auth::id()], ['id_program' => $post['id_program']]);
}
Every user can add to table max 6 favorite id programms
Add an unique index on the table:
ALTER TABLE `tableName` ADD UNIQUE `unique_index`(`id_user`, `id_program`);
and use the INSERT INTO ... OR UPDATE:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE t1 SET c=c+1 WHERE a=1;
In that manner your query will insert a new record if there isn't already a record with the same couple of id_user and id_program values, in case of it it'll perform an update on that row.
If you want to do it in PHP and assuming your values are stored in an array, you can use array_unique().
Check it out here: http://php.net/manual/en/function.array-unique.php
I have 2 database tables
tbl1 users ---------- tbl2 gamesystems
uid field ------------- gs_uid field
the 2 tables are tied together by the user_id..
now i want tbl2 to only be updated able and fields are not required.. with the exception of the gs_uid when they update there system.
my only issue is i need to insert the user_id into the gs_uid.
function game_system()
{
if(isset($_POST['game_system'])) {
$user_id = $_SESSION['uid'];
$motherboard = escape($_POST['motherboard']);
$processor = escape($_POST['processor']);
$memory = escape($_POST['memory']);
$graphics = escape($_POST['graphics']);
$harddrive = escape($_POST['harddrive']);
$power = escape($_POST['powersupply']);
$cooling = escape($_POST['cooling']);
$towercase = escape($_POST['towercase']);
$sql = "INSERT INTO gamesystem(gs_uid, motherboard, processor, memory, graphics, harddrive, powersupply, cooling, towercase) ";
$sql .= "VALUES('{$user_id}','{$motherboard}','{$processor}','{$memory}','{$graphics}','{$harddrive}','{$power}','{$cooling}','{$towercase}') ";
$result = query($sql);
}
}
If gs_uid is the primary key of table 'gamesystem' , then this field should not accept empty data.
Otherwise, if gs_uid is NOT the key, what's the primary key of this table? In case of UPDATE, you'll need to specify which row you'd like to update, otherwise the system will not know how to do so.
the SQL should looks like below
UPDATE "gamesystem"
SET "gs_uid" = $user_id
WHERE YOUR_PRIMARY_KEY_COLUMN = SPECIFIC VALUE;
I am trying to insert a tuple into PostgreSql using PHP. After inserting the tuple I want to get the value of one of the columns of the inserted row. This column value is generated automatically by the db as it is defined as SERIAL in DDL.
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
The table 'posts' has following DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
I want to get the value of 'postID' column when I insert a row into the table 'posts' to perform additional functions based on postID. I have tried pg_fetch_assoc, pg_fetch_row, pg_fetch_object & pg_fetch_array. None of those seem to work. (I made appropriate modifications to the code when using each of those functions.)
Is there something incorrect in the code or perhaps I am missing something?
Thanks!
A good way is the returning clause:
INSERT INTO posts
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;
My PHP is a bit rusty, but it'd look something like:
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
$row = pg_fetch_row($result);
$inserted_id = $row[0];
}
I wish to get the auto increment id from my db and call inside my controller.
The 'id' in db is primary key with auto increment.
I tried:
$id = $model->id;
$id = $model->find('id');
$id = $model->findByPK('id');
But the value is blank, any suggestion for me to get the correct id?
Reason why I need the id value is because I need id mix with other value and save into other column.
Thanks.
$newId = YourModel::find()->max('id') + 1;
AUTO_INCREMENT is a special value which may differ from the ID of the last record.
If records deleted, the AUTO_INCREMENT will still continue.
If records failed to insert, the AUTO_INCREMENT will still continue.
Assume you are using MySQL, you can see its value in phpMyAdmin.
Open a database, then a table.
Switch to the Operations tab.
Find the AUTO_INCREMENT field under Table options.
So you should obtain its value, especially when you depend on the AUTO_INCREMENT of your database.
For inserting one record, getting the LAST_INSERT_ID() could be an option. But I still don't prefer to do triple operations (insert, read ID, update). Better to minimize the I/O operations (read AUTO_INCREMENT, insert).
In my case, I need to import data from an Excel document. Surely, when performance is important, I cannot depend on the ActiveRecord model. So I use batchInsert() command.
I am adopting this answer for getting the AUTO_INCREMENT value in MySQL.
$lastModelId = Yii::$app->db->createCommand("
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'my_table'
")->queryScalar();
If using table prefix:
$lastModelId = Yii::$app->db->createCommand("
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :TableName
")->bindValues([
':TableName' => MyModel::getTableSchema()->name,
])->queryScalar();
The easiest way would be to get the new ID after saving the record. After that you can do what you need and save it again. Sth like this:
<?
$model = new YourModel;
$model->field1 = 'some value';
$model->field2 = 'some value 2';
//...
$model->save();
// now you have the new ID and you can use it
$id = $model->id;
// do what you need e.g.
$model->field3 = $field2 + $id;
$model->save();
?>
this worked for me.
public static function getAutoIncrement($table_name)
{
$q = new Query();
$res = $q->select("AUTO_INCREMENT")
->from('INFORMATION_SCHEMA.TABLES')
->where("TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '" . $table_name . "'")
->one();
if($res)
return $res["AUTO_INCREMENT"];
return false;
//or use this
//$q = "SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '" . $table_name . "'";
//$auto_increment = Yii::$app->db->createCommand($q)->queryScalar();
//return $auto_increment;
}
I found my own aswer:
$max = Yii::app()->db->createCommand()->select('max(id) as max')->from('TABLENAME')->queryScalar();
$id = ($max + 1);
print_r($id);
Thanks.
You are going about this the wrong way...
$model->id This is available if you have instantiated the $model prior so:
$model = new Model();
$id = $model->id; //this will work if id is the exact name of the column in db
$model->find('id') This finds elements in DB based on the id... but the syntax in wrong so it would throw an error
$model->findByPK('id') Again... find by pk returns a single row from DB if a match with the primary key (which you should have before making this call)
In conclusion, I would recommend the first way but do not forget to instantiate the model first. Otherwise, you can do something like...
$model = Model::model()->findByAttributes(array('some_attribute' => $attribute_value));
$id = $model->id;
Hope this helps!
Keep on coding!
Ares.
How can insert the unique row in mysql?
id and userid both are different column.
I have set id is unique.But userid and checkin column should not be repeated.
Is this possible?
if($this->dx_auth->is_logged_in()){
$insertData['userid'] = $this->dx_auth->get_user_id();
$insertData['checkin'] = $checkin;
$insertData['checkout'] = $checkout;
$insertData['location'] = $location;
$insertData['guest'] = $nof_guest;
$id = $this->dx_auth->get_user_id();
$result = $this->Common_model->getTableData('searchlist', array("userid" => $id));
if($result->num_rows > 4){
$res = $result->result();
$del_id = $res[0]->id;
$conditions = array("id" => $del_id);
$this->Common_model->deleteTableData('searchlist', $conditions);
}
if($location != "0"){
$this->Common_model->inserTableData('searchlist', $insertData);}}
You can keep your id as primary key and auto increment for your user table.
Then, you have to create combined unique key for userid and checkin.
CREATE UNIQUE INDEX user_checkin_time ON searchlist (userid, checkin);
In controller, you have to validate the userid and checkin before insert / update.
$isExist = $this->Common_model->getTableData('searchlist', array("userid" => $id,"checkin"=>$checkin));
if($isExist->num_rows()>0)
{
// throw error message as checkin time already exist
}
else
{
// continue with further code
}
In this case, you can really make the userid and checkin columns as a composite primary key. If you want you can still use id as the primary key and create a unique index for the 2 other columns combined.
You should probably also check if the record exists before you insert a new combination that would result in a MySQL error.
Cheers!