I can not insert data into mysql because of database error 1048.I have been searching from almost 1 week, but i couldn't find any solution. please help me. Here is all the stuff...
controller users.php:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller
{
function __construct()
{
parent::__construct();
#$this->load->helper('url');
$this->load->model('users_model');
}
public function index()
{
$data['user_list'] = $this->users_model->get_all_users();
$this->load->view('show_users', $data);
}
public function add_form()
{
$this->load->view('insert');
}
public function insert_new_user()
{
$udata['Username'] = $this->input->post('name');
$udata['Email-Id'] = $this->input->post('email');
$udata['Address'] = $this->input->post('address');
$udata['Mobile'] = $this->input->post('mobile');
$res = $this->users_model->insert_users_to_db($udata);
if($res)
{
header("location: http://localhost/crudcode/index.php/users_model/insert_users_to_db");
}
else
{
echo "Hello";
}
}
}
Model users_model.php:
<?php
class Users_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_users()
{
$query = $this->db->get('users');
return $query->result();
}
public function insert_users_to_db($udata)
{
return $this->db->insert('users', $udata);
}
public function getById($id)
{
$query = $this->db->get_where('users',array('id'=>$id));
return $query->row_array();
}
}
?>
view insert.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CI Insert Form</title>
</head>
<body>
<form method="post" action="localhost/crudcode/index.php/users/insert_new_user">
<table width="400" border="0" cellpadding="5">
<tr>
<th width="213" align="right" scope="row">Enter your username</th>
<td width="161"><input type="text" name="name" size="20" /></td>
</tr>
<tr>
<th align="right" scope="row">Enter your email</th>
<td><input type="text" name="email" size="20" /></td>
</tr>
<tr>
<th align="right" scope="row">Enter your Mobile</th>
<td><input type="text" name="mobile" size="20" /></td>
</tr>
<tr>
<th align="right" scope="row">Enter Your Address</th>
<td><textarea name="address" rows="5" cols="20"></textarea></td>
</tr>
<tr>
<th align="right" scope="row"> </th>
<td><input type="submit" name="submit" value="Send" /></td>
</tr>
</table>
</form>
</body>
</html>
Here is the error
Have you check if the data from the form is submitted? like
public function insert_new_user()
{
print_r($this->input->post());
}
and check the array you've pass on the user model and the last query as well.
public function insert_users_to_db($udata)
{
$this->db->insert('users', $udata);
print_r($udata);
echo $this->db->last_query();
}
You Can try with changing the FORM action from
<form method="post" action="localhost/crudcode/index.php/users/insert_new_user">
TO
<form method="post" action="<?php echo base_url();?>index.php/users/insert_new_user" >
I am assuming you are not submitting an empty form.
The problem could be that there is a redirect happening which is not carrying your $POST data.
Have you tried using this as an action (with the right trailing /):
http://localhost/crudcode/index.php/users/insert_new_user/
You're calling the insert_user_to_db() twice.
First with:
$res = $this->users_model->insert_users_to_db($udata);
and in this call you're sending the values from the $udata array.
And then with:
if($res)
{
header("location: http://localhost/crudcode/index.php/users_model/insert_users_to_db");
}
and this call does not include any arguments so it's probably in this call it fails.
What happens if you exclude the second call and just to like this?
$res = $this->users_model->insert_users_to_db($udata);
echo print_r($res, true);
Genereally speaking you should not need/should not redirect to a model. Those kind of redirects should be handled by the controller(s).
1)Better to use form_open() and form_close().
2)Check Array which you are inserting.Columns names should match with the assoc array.
I believe Email-Id is an invalid field name. If you have named a field that way, you must escape it like:
`Email-Id`
or more accurately:
$udata['`Email-Id`'] = $this->input->post('email');
Though a much better solution is to rename the field, because that isn't even a naming convention. Either use only CamelCase or only underscore_names. A dash not a valid character for a field/variable name in any language I know of.
Related
I have a problem with my PHP project with CodeIgniter.
I have a form in which I pass variables to the Database and execute an UPDATE Query by modifying the data on the Database.
The problem is that when I insert the new data it does not give me error, it shows me the view in which it shows the data of the table but the data are not modified.
Can anyone help me understand please?
MODELS Hello_Model.php
function displayrecordsById($id)
{
$query=$this->db->query("SELECT * FROM Todolist WHERE id='".$id."'");
return $query->result();
}
function updaterecords($testo,$stato,$id)
{
$this->db->query("update Todolist SET testo='$testo',stato='$stato' WHERE id='".$id."'");
}
Views update_records.php
<html>
<head>
<title>Registration form</title>
</head>
<body>
<?php
//$i=1;
foreach($data as $row)
{
?>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="230">Id </td>
<td width="329"><input type="text" name="id" value="<?php echo $row->id; ?>"/></td>
</tr>
<tr>
<td>Testo </td>
<td><input type="text" name="testo" value="<?php echo $row->testo; ?>"/></td>
</tr>
<tr>
<td>Stato</td>
<td><input type='text' name='stato' value= "<?php echo $row->stato; ?> "/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="update" value="Update Records"/></td>
</tr>
</table>
</form>
<?php } ?>
</body>
</html>
</html>
Controllers Hello.php
public function updatedata()
{
$id=$this->input->get('id');
$result['data']=$this->Hello_Model->displayrecordsById($id);
$this->load->view('update_records',$result);
if($this->input->post('update'))
{
$n=$this->input->post('testo');
$e=$this->input->post('stato');
$this->Hello_Model->updaterecords($id,$n,$e);
redirect("http://simone.fabriziolerose.it/index.php/Hello/dispdata");
echo "Success!";
}
}
I took the code from this tutorial
i think problem in calling model function check:
change this:
$this->Hello_Model->updaterecords($id,$n,$e);
To
$this->Hello_Model->updaterecords($n,$e,$id);
and you change your custom query to CI query like:
For Update
$this->db->where("id",$id);
$this->db->update("Todolist",array("testo"=>$testo,"stato"=>$stato));
For Select:
$this->db->where("id",$id);
$query=$this->db->get("Todolist");
$row=$query->row();
View:
Any one help me to solve this issue,i'm getting following error A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: users/dataupdate.php
Line Number: 5
This is my view page
dataupdate.php:
<form method="post" action="<?php echo base_url();?>user_controller/dataupdate/<?php echo $id;?>">
<table width="280" border="1" align="center">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php $result->name;?>"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="test" name="cnum" value="<?php $result->email;?>></td>
</tr>
<tr>
<td>mobile</td>
<td><input type="password" name="pass" value="<?php $result->mobile;?>></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="sub" value="Submit"></td>
</tr>
</table>
</form>
This is my controller
user_controller.php:
<?php
class user_controller extends CI_controller
{
function __construct()
{
parent:: __construct();
//$this->load->helper('form');
//$this->load->helper('url');
$this->load->model('user_model');
}
function add()
{
$data['title']="add";
$this->form_validation->set_rules("name","Name","required");//text fildname,userdefine name
$this->form_validation->set_rules("email","email","required");
$this->form_validation->set_rules("password","password","required");
$this->form_validation->set_rules("mobile","mobile","required");
if($this->form_validation->run())
{
$this->user_model->insert($_POST);
redirect("user_controller/display");
}
$this->load->view('users/add',$data);
}
function display()
{
$data['result']=$this->user_model->datadisplay();
$this->load->view('users/datadisplay',$data);
}
function deletedata($id)
{
$data['result']=$this->user_model->deletequery($id);
redirect("user_controller/display");
}
function updatedata($id)
{
$data['result']=$this->user_model->datadisplay(array("id"=>$id));
if($this->form_validation->run())
{
$_POST['id']=$id;
$id=$this->user_model->update($_POST);
}
$data['id']=$id;
$this->load->view('users/dataupdate',$data);
}
}
?>
This is my model
user_model.php:
<?php
class user_model extends CI_model
{
function insert($options=array()){
if(isset($options['name']))//userdefine name
$this->db->set('name',$options['name']);//db colomn name,text field name
if(isset($options['email']))
$this->db->set('email',$options['email']);
if(isset($options['password']))
$this->db->set('password',md5($options['password']));
if(isset($options['mobile']))
$this->db->set('mobile',$options['mobile']);
$this->db->insert('user');
return $this->db->insert_id();
}
function datadisplay()
{
$this->db->select('*');
$this->db->from('user');
if(isset($options['id']))
$this->db->where('id',$options['id']);
$query=$this->db->get();
return $query->result();
}
function deletequery($id)
{
$this->db->delete('user',array('id'=>$id));
}
function update($options=array())
{
if(isset($options['name']))//userdefine name
$this->db->set('name',$options['name']);//db colomn name,text field name
if(isset($options['email']))
$this->db->set('email',$options['email']);
if(isset($options['mobile']))
$this->db->set('mobile',$options['mobile']);
if(isset($options['id']))
$this->db->where('id',$options['id']);
$query=$this->db->update('user');
return $query;
}
}
?>
you should assign value into another variable than use it.
<?php
$tempname = $result[0]->name;
$email = $result[0]->email;
$mob = $result[0]->mobile;
?>
<form method="post" action="<?php echo base_url();?>user_controller/dataupdate/<?php echo $id;?>">
<table width="280" border="1" align="center">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $tempname;?>"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="test" name="cnum" value="<?php echo $email;?>></td>
</tr>
<tr>
<td>mobile</td>
<td><input type="password" name="pass" value="<?php echo $mob;?>></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="sub" value="Submit"></td>
</tr>
</table>
</form>
When you get the message "trying to get the property of a non-object" in PHP, it means that you are trying to access an attribute of an object, where the object does not exist.
Consider this as an example. An object Car $car exists in your code and a Car object has a public attribute $speed. Normally you can access speed of the $car object by $car->speed. If somehow $car is set to null or some other value, where it is not a Car object, you will receive the error when attempting to access the $speed attribute of a Car.
Before you attempt to access the speed attribute you could do something like:
if (is_a($car, 'Car')) {
//do whatever you want when $car is a Car object
} else {
//do whatever you want when $car is not a Car object
}
You could also use this:
if ($car instanceof Car) {
//do whatever you want when $car is a Car object
} else {
//do whatever you want when $car is not a Car object
}
And finally, you can do this, which will suppress the exception, when $car is not a Car object:
if (#$car->speed)
//do whatever you want when $car is a Car object
} else {
//do whatever you want when $car is not a Car object
}
If $car is always supposed to be a Car object, and you're receiving the error, the best thing to do would be to avoid all of the additional logic and determine where your $car object is being corrupted and fix it.
simply you can use the object or variable like #$variable
<input name="ftp_name" value="<?php echo $ftpDetails->ftp_name;?>" type="text">
change to:
<input name="ftp_name" value="<?php echo #$ftpDetails->ftp_name;?>" type="text">
The following error :
Fatal error: Call to undefined function add() in E:\xampp\htdocs\paperblog\Admin\AddNewPost.php on line 18
line 18 :
$msg=add($title,$subtitle,$details,$_FILES['_postImage']);
The whole codes (HTML
,PHP)are in the following lines.
I've 4 files:
The AddNewPost.php file is the main file has the HTML code.
Has PHP code :
<?php
include_once("..\DB.php");
include_once("..\Classes\post.php");
$title="";
$subtitle="";
$details="";
$msg="";
if(isset($_POST['_PostSubmit']))
{
$title=$_POST['_PostTitle'];
$subtitle=$_POST['_PostSubTtile'];
$details=$_POST['_PostDetails'];
if( !empty($title)||!empty($subtitle)||!empty($details) )
{
$msg=add($title,$subtitle,$details,$_FILES['_postImage']);
}
else
$msg=" The post is empty ";
}
include_once("Header.php");
?>
And HTML:
<form action="AddNewPost.php" method="post" id="cmntfrm" enctype= "multipart/form-data">
<P align="center" style="color:#F00"><?=$msg?></P>
<p> </p>
<table width="600" border="0" align="center">
<img src="../images/addNewPost.png"/>
<br />
<br />
<tr>
<td width="131">Post Title <h8 style="color:#F00">*</h8>:</td>
<td width="443"><input name="_PostTitle" type="text" /></td>
</tr>
<tr>
<td>Post Sub Title <h8 style="color:#F00">*</h8>:</td>
<td><input name="_PostSubTtile" type="text" /></td>
</tr>
<tr>
<td>Post Details :</td>
<td><textarea name="_PostDetails" cols="32" rows="7"> </textarea></td>
</tr>
<tr>
<td>Post Image :</td>
<td><input name="_postImage" type="file"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td></td>
<td><input name="_PostSubmit" type="submit" value="Save" id="submit" /></td>
</tr>
</table>
<center>
<img src="../Post_Imges/a.jpg" height="420" width="460" />
</center>
Thepost.php file which has functions of the post form where is in the classes folder. It Has PHP code:
<?php
include_once("../DB.php");
class post{
var $Post_ID;
var $title,$subtitle,$postdetail,$Post_Imgs;
var $pmonth ,$pyear ,$pday;
function add($title,$subtitle,$postdetail,$file){
$query=" insert into post(Title,SubTitle,PostDetails,PDay,PMonth,PYear)
values('$title,'$subtitle','$postdetail'".date("d").",".date("m").",".date("Y").")";
$this->Post_ID=$this->GetLastPostId();
$msg=test("Add",$query);
$msg.="<br/>".$this->uploadImage($file);
return $msg;
}
function GetLastPostId(){
$query="select Max(Post_ID) from Post";
$result=mysql_query($query);
$row=mysql_fetch_row($result);
return $row[0];
}
function uploadImage($file){
uploadFile("Post_Imges\$Post_ID.jpg",$file);
}
}
?>
3.The DB.php file which has some function for DB. It has :
<?php
include_once("functions.php");
mysql_connect("localhost","root","");
mysql_select_db("paperbloge");
function test($test ,$query){
mysql_query($query);
if(!empty(mysql_errno()))
return "Post ".$test." Successfully" ;
else
return "Error".mysql_errno().":".mysql_error();
}
?>
Finaly, functions.phpfile which has uploadfile function.
function uploadFile($folderPathFileName,$file){
if (!empty($file['tmp_name'])){
move_uploaded_file($file['tmp_name'],$_SERVER['DOCUMENT_ROOT']."\paperblog\ ".$folderFileName);
$msg.="<br/> Image uploaded Successfully";
}
else
$msg= "Image File too large or No Image File";
return $msg;
}
?>
Thats the whole codes that i've .
Does anyone know what is wrong here that cause this problem?
Thanks
Ya it's working , But have some errors again .
Thanks for your helping .
add() is not a function. It is a method of a class called "post". That means you have to instantiate that class and then call that method:
$post = new Post();
$msg=$post->add($title,$subtitle,$details,$_FILES['_postImage']);
add is part of the class post
Change your line to;
$objPost = new post();
$msg = $objPost->add($title,$subtitle,$details,$_FILES['_postImage']);
Ok i have a session class that currently handles setting variables, getting variables, deleting them and destroying them. I have a form which take information from a user and i am not sure how i would get the post variables using a session class rather than just using $_SESSION{'some variable'] to set the variables and use them.
<?php
class sessionClass{
public function _constructor()
{
session_start();
}
public function destroy()
{
session_destroy();
}
public function add($name, $value)
{
if(empty($name)){
die('Invalid variable name');
}
$_SESSION[$name] = $value;
}
public function delete($name)
{
session_unset ($_SESSION[$name]);
}
public function get($name)
{
if(isset($_SESSION[$name]))
$_SESSION[$name] = $name;
else
return ($_SESSION[$name]);
}
}
?>
Above is my session class. Now i am trying to use OOPHP and i am trying to validate the data being entered into my template form page. However because i am passing the variables $_POST['LoginID'] and $_POST['Password'] i am getting these errors.
Notice: Undefined index: LoginID in /home/comp3170-020/public_html/assignment2/index.php on line 20 Notice: Undefined index: LoginID in /home/comp3170-020/public_html/assignment2/index.php on line 25 ect ect
//Creating class objects
$val = new validatorClass();
$ses = new sessionClass();
$dis = new XHTMLDisplayClass();
$dis->setTemplate('templates/index.tpl.php');
//Checking that data is validated
if (isset($_POST['Submit']))
{
if ((!$val->isValidLoginID($_POST['LoginID'])) || (!$val->isValidLoginIDE($_POST['LoginID'])) ||(!isValidPassword($_POST['Password'])))
{
$errs = $val->getErrorMessages();
$d-> addVar('errors', $errs);
}
else {
//$ses = new sessionClass();
$ses->add('LoginID', $_POST['LoginID']);
$ses->add('Password',$_POST['Password'] );
$ses->add('validationDone', true);
header('Location:auth.php');
exit;
}
}
Can anyone tell me how i should pass the variables to the functions of the classes.
form code :
<form name="form1" action="index.php" method="POST">
<td width="220" class="content_l">Login ID</td>
<font color = "FF0000">
<?php if (isset ($errors['isValidLoginID'])){echo $errors['isValidLoginID'];}?>
<?php if (isset ($errors['isValidLoginIDE'])){echo $errors['isValidLoginIDE'];}?>
<?php if (isset ($errors['isValidPassword'])){echo $errors['isValidPassword'];}?>
</font>
</tr>
<tr>
<td><input type="text" name="textfield" class="form250"></td>
</tr>
<tr>
<td height="25" valign="bottom" class="content_l">Password</td>
</tr>
<tr>
<td><input type="password" name="textfield" class="form250" ></td>
</tr>
<tr>
<tr>
<td height="25" valign="bottom" class="content_1">Identification Used</td>
</tr>
<tr>
<td><input type="radio" name="authtyp" value="Username" class="form250" <?php echo $usertyp?> checked>Username <input type="radio" name="authtyp" value= "Email" class="form250" <?php echo $emailtyp?>> Email</td>
</tr>
<tr>
<td height="40" valign="bottom">
<input type="submit" name="Submit" value="LOGIN" class="btn70" style="margin-top:10px; ">
</form>
</td>
</tr>
<tr>
<td height="30" valign="bottom">Forgot your password? </td>
</tr>
</table></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
I'm learning PHP and am having issues getting the following code to work properly. Basically the login page displays correctly, and without errors and the variables appear to be assigned correctly, but upon page reload I just get the same login form, it appears the data has either not been passed and is therefore not being acted upon.
I've looked at the code over and over again and even tried a different method (produced same result!) so it'd be lovely if someone helpful could spend a minute and point me in the right direction.
One thing that might be an issue is my server is running 5.3.9 and the book I'm working from is PHP5 so maybe some of the function I'm calling have been deprecated. Which would be a pain...
<?php
include_once "common_db.inc";
$register_script = "register.php";
if (!isset ($userid)) {
login_form();
exit;
} else {
session_start();
session_register ("userid", "userpassword");
$username = auth_user ($_POST['userid'], $_POST['userpassword']);
if (!$username) {
$PHP_SELF = $_SERVER['PHP_SELF'];
session_unregister ("userid");
session_unregister ("userpassword");
echo "Failed to authorize. " .
"Enter a valid DX number and password." .
"Click the link below to try again.<br>\n";
echo "login<br>";
echo "Click the following link to register<br>\n";
echo "Register";
exit;
} else {
echo "Welcome, $username!";
}
}
function login_form()
{
global $PHP_SELF;
?>
<form method="post" action="<?php echo "$PHP_SELF"; ?>">
<div align="center"><center>
<h3>Please login to use the page you requested</h3>
<table width="200" cellpadding="5">
<tr>
<th width="18%" align="right" nowrap>id</th>
<td width="82%" nowrap>
<input type="text" name="userid" />
</td>
</tr>
<tr>
<th width="18%" align="right" nowrap>password</th>
<td width="82%" nowrap>
<input type="password" name="userpassword" />
</td>
</tr>
<tr>
<td colspan="2" width="100%" nowrap>
<input type="submit" value="login" name="Submit" />
</td>
</tr>
</table>
</center>
</div>
</form>
<?php
}
function auth_user($userid, $userpassword)
{
global $dbname, $user_tablename;
$link_id = db_connect($dbname);
$query = "SELECT DXNumber FROM $user_tablename WHERE DXNumber = '$userid'
AND userpassword = password ('$userpassword')";
$result = mysql_query ($query);
if (!mysql_num_rows($result)){
return 0;
}else{
$query_data = mysql_fetch_row($results);
return $query_data[0];
}
}
?>
You're not defining $userid or checking if the form has been submitted. Try:
if (!isset($_POST['userid'])) {
Your query in your auth_user function needs to look like this:
$query = "SELECT DXNumber FROM $user_tablename WHERE DXNumber = '$userid' AND userpassword ='" . $userpassword."'";
Also, you're open to sql injection. You should look into using PDO and prevent it.
try
if (!isset $_POST['userid']) {
and see if that helps. It looks like $userid is not being set before you branch.
(edited because of stupid spelling checker.)