Integrity constraint violation when ID does exist - sql

After searching around, it seems like the problem is that the id doesn't exist in table 1 when inserting into table 2 BUT it does exist in my table! Actually this was working fine for few months until yesterday.
Error: Cannot add or update a child row: a foreign key constraint fails review CONSTRAINT reviews_ibfk_1 FOREIGN KEY (user_id) REFERENCES user(user_id))
public function actionAjaxComment($id) {
$prod_id= $id;
if(Yii::app()->request->isAjaxRequest) {
$model=new Review;
$this->performAjaxValidation($model);
$user_id = Yii::app()->user->user_id;
$criteria = new CDbCriteria;
$criteria->compare('target_product_id',$prod_id);
$criteria->compare('user_id',$user_id);
$record = $model->findAll($criteria);
$model->attributes=$_POST['Review'];
if(empty($record)) {
$date = Yii::app()->getDateFormatter()->formatDateTime(time(), 'long', 'short');
$model->user_id = $user_id;
$model->target_product_id = $prod_id;
$model->review_date = time();
$uname = ucwords(Yii::app()->user->username);
$img = User::model()->FindByPk($user_id)->image;
$img_url = Yii::app()->basePath."/images/user/".$img;
$img = Yii::app()->assetManager->publish($img_url);
$model->save();
echo CJSON::encode(
array('status'=>'success',
'star'=>$model->star,
'review'=>$model->review,
'user'=>$uname,
'uimg'=>$img,
'date'=>$date,
));
return $model->review;
} elseif(!empty($record)) {
echo CJSON::encode(
array('status'=>'dup'
));
} else
echo CJSON::encode(
array('status'=>'error'
));
Yii::app()->end();
}
}

Is your user_id a foreign key? If yes, the maybe the table which it points to doesn't have a row with the user id you are trying to assign it to

Related

How can I add to an existing value in sql table

How can i add a value to an existing value in SQL example a value 4 in a column how can i add 2 to it to make it 6 not to update to 2 but to add the previous value and the new value to together here is my class php file
<?php
class data
{
public $d_count;
public $id;
private $conn;
private $table_name;
public function __construct($db)
{
$this->conn = $db;
$this->table_name= "tbl_data";
}
public function updateCount()
{
// $query = "UPDATE tbl_data SET d_count = ?, date_updated = ? WHERE id = ?";
$query = "UPDATE tbl_data SET d_count '+1' = ?, date_updated = ? WHERE id = ?";
$obj = $this->conn->prepare($query);
$this->d_count = htmlspecialchars(strip_tags($this->d_count));
$this->date_updated = htmlspecialchars(strip_tags($this->date_updated));
$this->id = htmlspecialchars(strip_tags($this->id));
$obj->bind_param("sss", $this->d_count, $this->date_updated, $this->id);
if ($obj->execute()) {
return true;
}
return false;
}
}
The line I commented out is what i used to test the code and it works fine but now i need to add the old value + new value together here is the code am using to update the table
<?php
$data = new data($connection);
if($_SERVER['REQUEST_METHOD'] === "POST"){
$newDCount = json_decode(file_get_contents("php://input"));
if(!empty($newDCount->d_count))
$data->id= $newDCount->id;
$data->d_count = $newDCount->d_count;
$data->date_updated = date('Y-m-d H:i:s', time());
if($apiata->updateCount()){
http_response_code(200);
echo json_encode(array(
"status" => 200,
"message" => "Success"
));
}
else
{
http_response_code(200);
echo json_encode(array(
"status" => 500,
"message" => "Failed"
));
}
}
To update the d_count to add to the existing d_count value, the query should look like:
$sql = 'UPDATE catalog SET d_count = d_count + ?, date_updated = ? WHERE id = ?';
The other handling should be ok as-is.

Laravel where query not working

I've got this table
beds
id
name
size
room
status
hotel
created_at
updated_at
I need to filter all beds that belong to a certain room. In order to do so, I've coded this lines.
public function index()
{
//
$user = JWTAuth::parseToken()->authenticate();
$data = Input::get('room');
if( $data ){
$beds = Bed::where('room', '=', $data )->get();
}else{
$beds = Bed::where('hotel', '=', $user->hostel )->get();
}
foreach( $beds as $bed) {
return $bed->get( array('size','room', 'id') );
}
}
So, If i give it the room id, it should return me only that room's ones.
The thing is that it's returning all table entries.
Any ideas?
UPDATE
Fixed relations and tried this:
return Room::with('beds')->findOrFail($data)->beds;
Now it gives me the number of items.
How can I get the items?
UPDATE
This is the model's code:
class Room extends \Eloquent {
protected $fillable = array('beds', 'price', 'name', 'description','hotel');
public function beds(){
return $this->hasMany('Bed', 'id', 'room');
}
}
UPDATE
The var_dump for:
var_dump( Room::with('beds')->findOrFail($data)->beds );
is:
int(1)
UPDATE
So, the final code is the following.
controller
public function index()
{
//
$user = JWTAuth::parseToken()->authenticate();
$data = Input::get('room');
if( $data ){
$d = intval( $data );
return Bed::where('room', '=', $d )->get( array('size', 'room', 'id', 'name') );
}else{
return Bed::where('hotel', '=', $user->hostel )->get( array('size', 'room', 'id', 'name') );
}
}
model
class Room extends \Eloquent {
protected $fillable = array('beds', 'price', 'name', 'description','hotel');
public function camas(){
return $this->hasMany('Bed', 'room', 'id');
}
}
Thank you guys!
You have quite a few issues in your attempts:
return $bed->get( array('size', 'room', 'id') );
// runs SELECT size, room, id from `rooms`
so it returns all the rooms (why on earth would you like to do this in a foreach anyway?)
return $this->hasMany('Bed', 'id', 'room');
// should be:
return $this->hasMany('Bed', 'room', 'id');
protected $fillable = array('beds', ...
public function beds(){
this is conflict - you will never get a relations when calling $room->beds since you have a column beds on your table.
that said, this is what you need:
public function index()
{
$user = JWTAuth::parseToken()->authenticate();
if(Input::has('room')){
$query = Bed::where('room', '=', Input::get('room'));
}else{
$query = Bed::where('hotel', '=', $user->hostel);
}
return $query->get(['size', 'room', 'id']); // given you need only these columns
}
Try this and see if it works. If not, can you provide the var_dump of Input::get('room') and the structure of the the beds table?
public function index()
{
//
$user = JWTAuth::parseToken()->authenticate();
$data = Input::get('room');
if( $data ){
$beds = Bed::where('room', '=', $data );
}else{
$beds = Bed::where('hotel', '=', $user->hostel );
}
return $beds->get(['size','room', 'id'])->toArray();
}
Better yet if you want to get specific beds in a room and you have your relations set up correctly:
return Room::with('beds')->findOrFail($data)->beds;
EDIT
I saw your update. Are you sure its giving you a number of items, maybe there is one item and the number is the id of it. Can you verify? Please provide a vardump of it if thats not the case. Also can you post your code for the relations in the model?

findall() in yii return array and i want it to return object how

i have w function called update that i want to update a specific record in database according to module id (m_id) and key (key)
here is the function
public function updateRecord($module,$key,$newData){
$id = $this->module($module);
$model = new Form;
$criteria = new CDbCriteria();
$criteria->condition = "`m_id` = 1 AND `key` = 'txt'";
// $model = Yii::app()->db->createCommand("SELECT * FROM `tbl_setting` WHERE `m_id` = 1 AND `key` = 'txt'")->query();
die(var_dump($model->findAll($criteria)));
// $model = Yii::app()->db->createCommand("SELECT * FROM `tbl_setting` WHERE `m_id` = 1 AND `key` = 'txt'")->execute();
$model->m_id = $id ;
$model->attributes = $newData;
$model->save();
//die(print_r($model['m_id']));
//if(isset($_POST['save'])){
//$model['m_id'] = $id;
//}
}
every time i try to use this function it give me error that $model is not an object so it can't execute
$model->m_id = $id ;
i check out the type of findAll() and it gives an array
i checkout all find() methods and only findByPk() that give an object
and i want to choose according to the $criteria and i don't know what to do any help ?! :)
findAll will always return an array. With objects if there are record found, or an empty array on no result. find only returns 1 record, or NULL if nothing is found:
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#find-detail
Your code will be save when you do it like this:
if(!is_null($model)) {
$model->m_id = $id ;
$model->attributes = $newData;
$model->save();
} else {
echo 'No record found';
}

PHP PDO dynamically updating db table with multiple records to a specific user ID

/* Newbie need some help; I am creating a class to auto update my apps db record when instructed to, but I am consistently getting this message below, and for the heck of it, I just not seeing what I am doing wrong. Can someone please look at my codes for me? Thank you.
Warning: PDOStatement::bindParam() expects at least 2 parameters, 1 given in……..on line 331; that where the "else if(is_string($val)){" is located.
*/
// vars given
// DBDriver: MySQL
$myTable = 'seeYou';
$loginDate = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
$date = #date('m/d/Y \a\\t h:i a');
$_id =1;
// data array
$idata = array("last_logged_in"=>$loginDate,
"login_date"=>$date,
"ip_addr"=>$ip
);
class name
{
///------------ other methods here---------///
/**
*--------------------------------------------
* Method - PDO: SET FIELD VALUE PLACEHOLDER
*--------------------------------------------
* #return fields with prefix as placeholder
*/
protected function set_fieldValPlaceHolders(array $data)
{
$set = '';
foreach($data as $field => $value)
{
$set .= $field .'= :'.$field . ',';
}
// remove the last comma
$set = substr($set, 0, -1);
return $set;
}
public function save($data=NULL, $_id = NULL, $rows= NULL, $dbTable= NULL)
{
//----------------- some other codes goes here ----------------//
$id = (int)$_id;
// update row with a specific id
if (isset($id) !== NULL && $rows === NULL)
{
$set = $this->set_fieldValPlaceHolders($data);
$sql = "UPDATE {$dbTable} SET {$set} WHERE user_id = :uid";
try
{
// Build the database statement
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindValue(':uid',$id, PDO::PARAM_INT);
foreach ($data as $field => $val)
{
if(is_int($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_INT');
}
else if(is_string($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_STR');
}
else if(is_bool($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_BOOL');
}
else if(is_null($val)){
$_stmt->bindValue(':'.$field.'\', '.$val="null".', PDO::PARAM_NULL');
}
else {
$_stmt->bindValue(':'.$field.'\', '.$val.', NULL');
}
$result = $_stmt->execute();
$num = $_stmt->rowCount();
}
}
catch(PDOException $e)
{
die('Error! The process failed while updating your record. <br /> Line #'.__LINE__ .' '.$e);
}
if ($result === true)
{
return true;
}
}
Check your bindValue calls: You give 1 parameter (a long string). It needs at least two. Check all the '
for example, it should be:
$_stmt->bindValue(':'.$field, $val, PDO::PARAM_INT);

how to fix update error

i want to update all row's alternativegroups with $id value.
the action getting error: coldchain can not be null.
when i search the db for pk = $a, It's coldchain value is boolen(false). and db is postgresql
how can i set $q->attributes without posting other values?
public function actionUpdate($id){
if (isset($_POST['forms'])){
$arr = explode(',', $_POST['forms']);
foreach ($arr as $a){
$q = MedicineDrugform::model()->findbypk($a);
$q->alternativegroup = $id;
if ($q->save()){
echo $q->id."q saved <br />";
}
else {
echo "<pre>";
print_r($q->getErrors());
}
die();
$qu = MedicineDrugformUpdate::model()->findbyattributes(array('drug_form_id'=>$a));
$quu = MedicineDrugformUpdate::model()->findbypk($qu->id);
$quu->alternativegroup = $id;
if ($quu->save()){
echo $quu->id."qu saved <br />";
}
}
die();
$this->render('/site/messages', array('message'=>'formsaved'));
}
$this->render('add', array('id'=>$id));
}
maybe it cant find the corresponding record for
$q = MedicineDrugform::model()->findbypk($a);