Deleting data from multiple table - mysql

I am trying to delete data from two different table at the same time but it seems like the query is not deleting data. First I will check either user have posted any blog and delete from user and blog if the query is true.
Here is my controller :
public function delete(){
if(isset($_SESSION['userLogId'])){
$selectedId = $this->uri->segment(3);
// getting the current image and unlink it if image exist
$currentImage = $this->User_account_model->currentImage('student', $selectedId);
if($currentImage != null){
$_SESSION['current_image'] = $currentImage->photo;
}
$isDeleted = $this->User_account_model->deleteUser($selectedId);
if($isDeleted == true){
if(isset($_SESSION['current_image']) && !empty($_SESSION['current_image'])){
unlink($_SERVER['DOCUMENT_ROOT']."/uploadfiles/users/student-img/".$_SESSION['current_image']);
unset($_SESSION['current_image']);
}
echo '<script>';
echo 'alert("User removed successfully.");';
echo 'window.location.href = "'.base_url('account/view-user/').'";';
echo '</script>';
} else {
echo '<script>';
echo 'alert("Error while removing. Deleting user unable to processed.");';
echo 'window.location.href = "'.base_url('account/view-user/').'";';
echo '</script>';
}
}
}
My model function to delete user :
function deleteUser($selectedId){
// first check either user have posted blog
$this->db->select('user_id');
$this->db->from('blog_content');
$this->db->where('user_id', $selectedId);
$query = $this->db->get();
$r = $query->row();
if(!empty($r)){
$this->db->delete('users_student, blog_content');
$this->db->from('users_student, blog_content');
$this->db->where('blog_content.user_id = users_student.id');
$this->db->where('users_student.id',$selectedId);
if($this->db->affected_rows()){
return true;
} else { return false; }
} else {
$this->db->delete('users_student');
$this->db->where('id',$selectedId);
if($this->db->affected_rows()){
return true;
} else { return false; }
}
}

In your deleteUser function, replace this code:
$this->db->delete('users_student, blog_content');
$this->db->from('users_student, blog_content');
$this->db->where('blog_content.user_id = users_student.id');
$this->db->where('users_student.id',$selectedId);
with this:
$this->db->delete('blog_content', array('user_id' => $selectedId));
$this->db->delete('users_student', array('id' => $selectedId));

I have solved my issue. It is the Codeigniter query format to delete.
Note : In Codeigniter delete query, specify WHERE first before DELETE
function deleteUser($selectedId){
// first check either user have posted blog
$this->db->select('user_id');
$this->db->from('blog_content');
$this->db->where('user_id', $selectedId);
$query = $this->db->get();
$r = $query->row();
if(!empty($r)){
// delete from blog first
$this->db->where('user_id',$selectedId);
$this->db->delete('blog_content');
if($this->db->affected_rows()){
// then delete from user
$this->db->where('id',$selectedId);
$this->db->delete('users_student');
if($this->db->affected_rows()){
return true;
} else { return false; }
}
} else {
$this->db->where('id',$selectedId);
$this->db->delete('users_student');
if($this->db->affected_rows()){
return true;
} else { return false; }
}
}

Related

Count number of views for each user

I have table 'viewlogs' which is formed from three field: ViewLogId, VideoId and UserId. ViewLogId has a primary key and AUTO_INCREMENT value. When a user watches a video its value increments. When a user watch a same video the viewLogId increments, but I want this value to increase only once and uniquely. How do I fix this problem. I've attached the table picture.
I used the following php code for updating the view_counts in the "videos" table. The above picture belongs to the viewlogs table.
public function updateStatistics($videoId, $fieldName, $userId)
{
$this->db->reconnect();
$this->db->trans_begin();
$this->db->query("UPDATE videos SET {$fieldName}={$fieldName}+1 WHERE VideoId=?", array($videoId));
if ($fieldName == "ViewCount" && $userId > 0) {
$this->db->insert('viewlogs', array('UserId' => $userId, 'VideoId' => $videoId, 'ViewDateTime' => date('Y-m-d H:i:s')));
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
return false;
}
I solved the problem, just need to check the user_id and video_id before updating the view.
public function updateStatistics($videoId, $fieldName, $userId)
{
$this->db->reconnect();
$this->db->trans_begin();
$sql = "SELECT * FROM viewlogs WHERE UserId ={$userId} AND VideoId ={$videoId}";
$query = $this->db->query($sql);
$result = $query->result_array();
if (empty($result)){
$this->db->query("UPDATE videos SET {$fieldName}={$fieldName}+1 WHERE VideoId=?", array($videoId));
if ($fieldName == "ViewCount" && $userId > 0) {
$this->db->insert('viewlogs', array('UserId' => $userId, 'VideoId' => $videoId, 'ViewDateTime' => date('Y-m-d H:i:s')));
}
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
return false;
}

I want to add another form for the logged in users inside session for codeigniter

I have this code -
if(isset($this->session->userdata['logged_in'])){
$this->load->view('admin_page');
}
Now I want to add new form which logged in users or admin can see. But when i adding form controller like below, its not working and not storing data into database table. The table is another separate table and and its not users table. So I have add the two separate database details In the same model file like this -
<?php
Class Login_Database extends CI_Model {
function SaveForm($form_data)
{
$this->db->insert('post', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
// Insert registration data in database
public function registration_insert($data) {
// Query to check whether username already exist or not
$condition = "username =" . "'" . $data['username'] . "'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {
// Query to insert data in database
$this->db->insert('users', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}
// Read data using username and password
public function login($data) {
$condition = "username =" . "'" . $data['username'] . "' AND " . "password
=" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($username) {
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>
Now how can i add the form when users logged in and they can see the form and when they fill up it, the value will save in database. I tried it but didn't work-
if(isset($this->session->userdata['logged_in'])){
// My form for separate table goes here
$this->load->view('admin_page');
}
What exactly is the problem? Are you getting any error message?
If the problem is that the form is not showing, then ensure the session is properly set.
If it has to do with the form not submitting, then try echoing the value of $data to be sure it's well formatted the way you wanted it. Note that it has to be an array of key=>value pair where key is the table column name and value is the value you want to insert.

fat models and thin controllers in codeigniter

this is a user.php controller
public function verifyLogin() {
if (isset($_POST["email"])) {
$e = $this->input->post("email");
$p = $this->input->post("pass");
$this->form_validation->set_rules("email", "email", "required|valid_email|xss_clean");
$this->form_validation->set_rules("pass", "password", "required|xss_clean");
if ($this->form_validation->run()) {
$data = array(
'select' => '*',
'table' => 'users',
'where' => "email = '$e' AND activated = '1'"
);
$checklogin = $this->query2->selectData($data);
if ($checklogin === FALSE) {
echo "quering userInfo fails. email is wrong or activation not done";
exit();
} else {
foreach ($checklogin as $row) {
$dbid = $row->id;
$dbusername = $row->username;
$dbpassword = $row->password;
$dbemail = $row->email;
if ($p === $dbpassword) {
$login_data = array(
'name' => $dbusername,
'email' => $dbemail,
'password' => $dbpassword,
'id' => $dbid,
'expire' => '86500',
'secure' => TRUE,
'logged_in' => TRUE
);
$this->input->set_cookie($login_data);
$this->session->set_userdata($login_data);
if ($this->session->userdata("logged_in")) {
$time = time();
$now = unix_to_human($time, TRUE, 'us');
$updateLogin = $this->query1->updateLogin($e, $now);
if ($updateLogin) {
echo "success";
} else {
echo 'update failed';
}
} else {
echo "session failed";
}
}else{
echo 'password incorrect';
}
}
}
} else {
echo "form validation fails";
}
} else {
$this->load->view('header');
$this->load->view('login');
$this->load->view('modal');
$this->load->view('footer');
}
}
this is model.php
public function selectData($data){
if(isset($data['direction'])){
$dir = $data['direction'];
}else{
$dir = "ASC";
}
if(isset($data['offset'])){
$off = $data['offset'];
}else{
$off = '0';
}
if(isset($data['select']) && isset($data['table'])){
$this->db->select($data['select'])->from($data['table']);
}
if(isset($data['where'])){
$this->db->where($data['where']);
}
if(isset($data['order_by_name'])){
$this->db->order_by($data['order_by_name'], $dir);
}
if(isset($data['limit'])){
$this->db->limit($data['limit'], $off);
}
$query = $this->db->get();
if($query){
$d = $query->result();
return $d;
}else{
return FALSE;
}
}
is this a good way of quering database?
i am new to mvc and i am reading everywhere about "fat models and this controllers"
what can be done to make it a good mvc architecture?
its only acceptable to echo out from the controller when you are developing:
if ($checklogin === FALSE) {
echo "quering userInfo fails.
if checking login is false then either show a view or go to a new method like
if ($checklogin === FALSE) {
$this->showLoginFailed($errorMessage) ;
the check login code in the controller is a great example of something that could be refactored to a model. then if you need to check login from another controller its much easier. putting the form validation code in a model would be another choice. often times when you are validating form code you are also inserting/updating to a database table -- so having all those details together in a model can make things easier long term.
"fat model" does not mean one method in a model that does a hundred things. it means the controller says -- did this customer form validate and insert to the database? yes or no? 3 lines of code.
the model has the code that is looking into the "fat" details of the form, validation, database, etc etc. say 50 or more lines compared to the 3 in the controller. but the methods in the model should still be clean: small and specific.

Yii2 password hash

I'd like to know how password hash is generated?
// This is my code:
$email="mail#example.net";
$password="mypassword";
// How to get password_hash variable?
$user = User::find()->where(['email'=>$email, 'password_hash'=>$password_hash])->one();
if(isset($user)){
echo "there is";
} else {
"Sorry!";
}
Thank you.
http://www.yiiframework.com/doc-2.0/guide-security-passwords.html Is how passwords are handled in Yii 2. Unless you're a crypto expert DO NOT try to write your own.
public function verifyPassword($password)
{
if(md5($password) === $this->password)
return TRUE;
else
return FALSE;
//return Yii::$app->security->validatePassword($password, $this->password);
}
public function beforeSave($insert)
{
// hash new password if set
if ($this->newPassword) {
//$this->password = Yii::$app->security->generatePasswordHash($this->newPassword);
$this->password = md5($this->newPassword);
}
// convert ban_time checkbox to date
if ($this->ban_time) {
$this->ban_time = date("Y-m-d H:i:s");
}
// ensure fields are null so they won't get set as empty string
$nullAttributes = ["email", "username", "ban_time", "ban_reason"];
foreach ($nullAttributes as $nullAttribute) {
$this->$nullAttribute = $this->$nullAttribute ? $this->$nullAttribute : null;
}
return parent::beforeSave($insert);
}
I use hash with md5 but i create function in user model
public function validatePassword($password)
{
return $this->PASSWORD === md5($password);
}

Hide mySQL error from invalid URL

I have a site with 300 articles stored in a mySQL database with the URL format of www.site.com/article1.html.
Most invalid URLs redirect succesfully to the main site. For example, www.site.com/article301 redirects to www.site.com, which is what I want.
But www.site.com/article301.html does not redirect anywhere. Instead it loads a blank article template and the following error at the top of the page:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home//public_html/site.com/functions.php on line 26
Line 26 and down reads
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
if(ENABLE_REWRITE == 1) $path=' » '.$row['name'].''.$path;
if(ENABLE_REWRITE == 0) $path=' » '.$row['name'].''.$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}
Any ideas how to fix this?
Here's the full code, as requested by King Skippus
<?php
/*function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT name, parent FROM categories WHERE id=$id");
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
$path=' » '.$row['name'].$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}*/
function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT * FROM categories WHERE id=$id");
if($result !== FALSE && mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
if(ENABLE_REWRITE == 1) $path=' » '.$row['name'].''.$path;
if(ENABLE_REWRITE == 0) $path=' » '.$row['name'].''.$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}
function get_categories_tree($id) {
static $categs = array ();
static $level=0;
$level++;
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']][0] = $row['id'];
$categs[$row['id']][1] = '/'.$row['nameurl'];
$categs[$row['id']][2] = str_repeat(' ', $level-1);
$categs[$row['id']][3] = $row['name'];
get_categories_tree($row['id']);
}
$level--;
return $categs;
}
function get_cats($id) {
$categs = array ();
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']][0] = $row['id'];
$categs[$row['id']][1] = '/'.$row['nameurl'];
// $categs[$row['id']][2] = str_repeat(' ', $level-1);
$categs[$row['id']][3] = $row['name'];
}
return $categs;
}
/*function login() {
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
return false;
} else {
$result=mysql_query("SELECT * FROM users WHERE login='{$_SERVER['PHP_AUTH_USER']}' AND password='{$_SERVER['PHP_AUTH_PW']}'");
if(mysql_num_rows($result)>0) return true;
else {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
return false;
}
}
}*/
function login() {
if (!isset($_SESSION['AUTH_USER']) || !isset($_SESSION['AUTH_PASS'])) return false;
else {
$result=mysql_query("SELECT * FROM users WHERE login='{$_SESSION['AUTH_USER']}' AND password='{$_SESSION['AUTH_PASS']}'");
if(mysql_num_rows($result)>0) return true;
else return false;
}
}
function get_categories($id) {
static $categs = array ("0" => "[Top]");
static $level=0;
$level++;
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']] = str_repeat('| ', $level-1).'|___'.$row['name'];
get_categories($row['id']);
}
$level--;
return $categs;
}
function get_parent_name($id) {
if($id!=0) {
$result=mysql_query("SELECT name FROM categories WHERE id=$id");
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
return $row['name'];
}
else return '-';
}
else return 'Top';
}
function getcatname($id, $table)
{
$r=mysql_query("SELECT title FROM $table WHERE id='$id'");
if(mysql_num_rows($r)>0) {
$row=mysql_fetch_array($r);
return $row['title'];
}
else
return "-";
}
?>
Probably your query failed, and you have no error handling. Your basic bare-bones query sequence should be:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
If you assume the query succeeded and blindly use $result later, you tend to get the type of errors you do, as mysql_query will return a boolean FALSE when something goes boom. That FALSE is not a valid statement handle, so the subsequent num_rows/fetch calls will also go boom.
Never assume a query has succeeded. Even if your sql syntax is 100% perfect, there's far too many other reasons for failure to NOT check.
Try replacing
if(mysql_num_rows($result)>0) {
with
if($result === FALSE) {
header('Location: http://www.example.com/');
}
else if (mysql_num_rows($result)>0) {
// Query was valid, but no rows returned. Take appropriate action.
}
EDIT
For troubleshooting purposes, what does it display if you change the function to this instead? Please be aware that this will intentionally break your site, but it will provide data that is useful for troubleshooting.
function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT * FROM categories WHERE id=$id");
die(sprintf("Value of id: %s, MySQL Error: %s",
var_dump($id, true), var_dump(mysql_error($result), true)));
// Leave the rest of your function as-is, just insert the line above.