php codeigniter don't update variable to mysql - php

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();

Related

Cannot delete row in database using PHP

I can't seem to delete row in database by id in php
I think the the id is not passed to the $_POST['delete']
however, the popup "Your data is deleted" is displayed, but the data is not deleted.
So I'm not sure where is the error in this code.
I also try to delete the data by its id
for example: Delete book where no='4';
and the code seems to run fine because the data is deleted in the database.
<html>
<script>
function confirmDelete() {
return confirm('Are you sure?');
}
</script>
<!DOCTYPE html>
<head>
<form action="test.php" method="POST">
<br><br><br>
<table bordercolor="#FFCC66" align="center" bgcolor="#FFFFFF">
<tr>
<th>No</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Donor's Name</th>
<th>Call Number</th>
<th>Date Received</th>
<th>Handled By</th>
<th></th>
<th></th>
</tr>
<?php
include ('config.php');
$view=mysqli_query($conn,"SELECT * FROM book");
?>
<?php while($v=mysqli_fetch_array($view)){ ?>
<tr>
<td>
<?php echo $v["no"];?>
</td>
<td>
<?php echo $v["title"];?>
</td>
<td>
<?php echo $v["author"];?>
</td>
<td>
<?php echo $v["year"];?>
</td>
<td>
<?php echo $v["donorname"];?>
</td>
<td>
<?php echo $v["callnum"];?>
</td>
<td>
<?php echo $v["datereceived"];?>
</td>
<td>
<?php echo $v["handledby"];?>
</td>
<td><input type="submit" name="delete" value="Delete" onclick="return confirmDelete('Are you sure?');" /></td>
</tr>
<?php
} ?>
</tr>
</table>
<br><br>
</form>
</body>
</html>
<?php
if(isset($_POST['delete']))
{
include('config.php');
$no =$v["no"];
$d=mysqli_query($conn,"DELETE FROM `book` WHERE no='$no'");
if ($d)
{
echo "<script type='text/javascript'> alert('Your data is deleted!'); </script>";
echo"<meta http-equiv='Refresh' content='0' >";
}
else
{
echo "<script type='text/javascript'> alert('Your data cannot delete!'); </script>";
}
mysqli_close($conn);
}
?>
Change the submit element to
<td>
<input type="submit" name="delete" value="<?php echo $v['no'];?>" onclick="return confirmDelete('Are you sure?');" />
</td>
and
$no = $_POST["delete"];
Another solution si to add a hidden input with your value.
<td>
<?php echo $v["no"];?>
<input type="hidden" value="<?php echo $v["no"];?>" />
</td>
In your php you will find the value in $_POST['no']
This solution is better to pass multiple arguments in POST like a captcha or a confirmation (checkbox).
logic is not correct, while you press the delete button, all the data will be passed along with submitting because your tag is outside of the loop.
As my opinion, you should use ajax like functionality here, or follow this method.
<?php while($v=mysqli_fetch_array($view)){ ?>
<form action="test.php" method="POST">
<tr>
<td>
<?php echo $v["no"];?>
<input type="hidden" value="<?php echo $v["no"];?>" name="no" >
</td>
<td><input type="submit" name="delete" value="Delete" onclick="return confirmDelete('Are you sure?');" /></td>
</tr>
</form>
<?php } ?>
and in your post call use $no = $_POST['no']; instead of $no =$v["no"];

MySQL table page not loading correct data

I'm creating a table that uses PHP to pull from a MySQL database that I have. I think I've got everything where I want it to be, however the only problem I'm having is that the results seem to be (for lack of a better word) "behind". What I mean by that is that my first page index.php is where I'm accepting user edits to the database. Once they click Update it sends them to my results.php file that is supposed to actually perform the SQL UPDATE and then display the updated table.
It updates the table just fine according to XAMPP's database editor. However, when I said "behind" I mean that the page loads, updates but doesn't display the updated data until either the user refreshes the page or returns to the first page THEN comes back. I'm not sure what could be causing it, so I'm hoping someone here can help me. I feel like the reason is something as simple as I'm just running the code in the wrong order, but I don't know for sure. My code is below:
index.php
<html>
<body>
<?php
include('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
?>
<form name="form1" method="post" action="results.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<input name="event_id[]" type="hidden" id="event_id" value="<?php echo $rows['event_id']; ?>">
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<input name="title[]" type="text" id="title">
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<input name="date[]" type="date" id="date">
</td>
<td align="center">
<input title="Use reference tables below to enter speaker ID" name="speaker[]" type="text" id="speaker">
</td>
<td align="center">
<input title="Use reference tables below to enter building ID" name="building[]" type="text" id="building">
</td>
<td align="center">
<input title="Use reference tables below to enter Room ID" name="room[]" type="text" id="room">
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Update" value="UPDATE"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<html>
<body>
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
?>
<form name="form1" method="post" action="index.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<?php echo $rows['title']; ?>
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<?php echo $rows['event_date']; ?>
</td>
<td align="center">
<?php echo $rows['speaker_name']; ?>
</td>
<td align="center">
<?php echo $rows['building_name']; ?>
</td>
<td align="center">
<?php echo $rows['room_name']; ?>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Return" value="Return"></td>
</tr>
</table>
</form>
</body>
</html>
Also if someone can give me some guidance as to how to run the htmlspecialchars function on my arrays within results.php I'd really appreciate it. I've already tried to create a for loop for literally each array but that didn't work. I've tried using ->
<?php
function htmlspecial_array(&$variable) {
foreach ($variable as &$value) {
if (!is_array($value)) { $value = htmlspecialchars($value); }
else { htmlspecial_array($value); }
}
}
but that also didn't work, and I've tried using the array_walk_recursive but to no avail. I want to try and do something like W3Schools' example here W3Schools Form Validation towards the bottom of the page where it says Validate Form Data With PHP and then gives an example.
The result you get from the UPDATE query is the number of affected rows in your database. To correctly display the updated data, you need to re-fetch from the database before you generate the HTML. You should rearrange your code in results.php like this:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
Side note: If your data is sensitive, you may want to read about mysqli prepared statement so hackers cannot tamper with your queries.
Regarding your question about htmlspecialchars, see Stackoverflow "Execute htmlspecialchars on a multi level array".

Can't update/change data in MySQL from PHP

I was almost there, but the update is not functioning well especially on the bottom part.
<?php
require('dbconnect.php');//Connects to the database
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysqli_query($link,"SELECT username FROM members WHERE username='$user_check'");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$loggedin_session=$row['username'];
if(!isset($loggedin_session))
{
header("Location: login.php");
}//To ensure that you must be logged in to access this page
?>
<html>
<head>
<title>Healing Food Form</title>
<meta charset="iso-8859-1"> <!--charset specifies characters available-->
<meta name="author" content="Klarenz Kristoffer M. Qui;ntildeones">
<meta name="description" content="form to update healing food">
<meta name="keywords" content="healing food,form">
</head>
<body>
<?php
$id=$_GET['hf_id'];
$query = "SELECT * FROM healingfood WHERE hf_id='$id'";
if(!mysqli_query($link,$query))
{
die("Sorry. There's a problem with the query.");
}
//stores the result of the query
$result = mysqli_query($link,$query);
while($record = mysqli_fetch_assoc($result))
{
$hf_id=$record['hf_id'];
$hf_title=$record['hf_title'];
$a_id=$record['a_id'];
$hf_image=$record['hf_image'];
$hf_description=$record['hf_description'];
$hf_benefits=$record['hf_benefits'];
$hf_source=$record['hf_source'];
?>
<form action="updatehealingfood.php?hf_id=<?php echo $record['hf_id']; ?>" method="POST">
<table id="container" align="center">
<caption>Update healing food</caption>
<tr>
<td>Title:</td>
<td><input name="hf_title" type="text" value="<?php echo $hf_title; ?>"><br></td>
</tr>
<tr>
<td>Author ID:</td>
<td><input name="a_id" type="text" value="<?php echo $a_id; ?>"><br></td>
</tr>
<tr>
<td>Image URL:</td>
<td><input name="hf_image" type="url" value="<?php echo $hf_image; ?>"><br></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea name ="hf_description" rows="18" cols="60"><?php echo $hf_description; ?></textarea><br></td>
</tr>
<tr>
<td>Benefits:</td>
<td><input name="hf_benefits" type="text" value="<?php echo $hf_benefits; ?>"><br></td>
</tr>
<tr>
<td>Source:</td>
<td><input name="hf_source" type="text" value="<?php echo $hf_source; ?>"><br></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" name="update" value="Update Healing Food"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
}
$id=$_GET['hf_id'];
if(isset($_POST['update']))
{
$hf_title=$_POST['hf_title'];
$a_id=$_POST['a_id'];
$hf_image=$_POST['hf_image'];
$hf_description=$_POST['hf_description'];
$hf_benefits=$_POST['hf_benefits'];
$hf_source=$_POST['hf_source'];
$query2="UPDATE healingfood SET hf_title='$hf_title', a_id='$a_id', hf_image='$hf_image', hf_description='$hf_description', hf_benefits='$hf_benefits', hf_source='$hf_source' WHERE hf_id='$id'";
$result2=mysql_query($query2) or die();
echo "Updated";
}
?>
When I was supposed to update the data, the data remains the same. No one changed. I don't get the $id=$_GET['hf_id']; .
What are my errors?
You are mixing mysqli_* and mysql_*.
At the first part you use mysqli_query(), later you use mysql_query() which has no connection to the database yet.
Stick to mysqli_*.
Change:
$result2=mysql_query($query2) or die();
to:
$result2=mysqli_query($link, $query2) or die( "MySQL error: " . mysqli_error($link) );

"Fatal error: Call to undefined function " Error

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']);

How to call php function from html form action?

I want to call php function in form action and i want to pass id as a argument. What I am doing is, in html form database column values will be displayed in text boxes, If I edit those values and click 'update' button values in database should be updated and 'Record updated successfully'message should be displayed in same page. I tried below code but not working. Let me know the solution. Thanks in advance.
<html>
<head>
<link rel="stylesheet" type="text/css" href="cms_style.css">
</head>
<?php
$ResumeID = $_GET['id'];
$con = mysql_connect("localhost", "root", "");
mysql_select_db("engg",$con);
$sql="SELECT * from data WHERE ResumeID=$ResumeID";
$result = mysql_query($sql);
$Row=mysql_fetch_row($result);
function updateRecord()
{
//If(!isset($_GET['id']))
//{
$NameoftheCandidate=$_POST[NameoftheCandidate];
$TelephoneNo=$_POST[TelephoneNo];
$Email=$_POST[Email];
$sql="UPDATE data SET NameoftheCandidate='$_POST[NameoftheCandidate]', TelephoneNo='$_POST[TelephoneNo]', Email='$_POST[Email]' WHERE ResumeID=$ResumeID ";
if(mysql_query($sql))
echo "<p>Record updated Successfully</p>";
else
echo "<p>Record update failed</p>";
while ($Row=mysql_fetch_array($result)) {
echo ("<td>$Row[ResumeID]</td>");
echo ("<td>$Row[NameoftheCandidate]</td>");
echo ("<td>$Row[TelephoneNo]</td>");
echo ("<td>$Row[Email]</td>");
} // end of while
} // end of update function
?>
<body>
<h2 align="center">Update the Record</h2>
<form align="center" action="updateRecord()" method="post">
<table align="center">
<input type="hidden" name="resumeid" value="<? echo "$Row[1]"?>">
<? echo "<tr> <td> Resume ID </td> <td>$Row[1]</td> </tr>" ?>
<div align="center">
<tr>
<td> Name of the Candidate</td>
<td><input type="text" name="NameoftheCandidate"
size="25" value="<? echo "$Row[0]"? >"></td>
</tr>
<tr>
<td>TelephoneNo</td>
<td><input type="text" name="TelephoneNo" size="25" value="<? echo "$Row[1]"?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="Email" size="25" value="<? echo "$Row[3]"?>">
</td>
</tr>
<tr>
<td></td>
<td align="center"><input type="submit" name="submitvalue" value="UPDATE" ></td>
</tr>
</div>
</table>
</form>
</body>
</html>
try this way
HTML
<form align="center" action="yourpage.php?func_name=updateRecord" method="post">
PHP
$form_action_func = $_POST['func_name'];
if (function_exists($form_action_func)) {
updateRecord();
}
write form action="" and then write your php code as below
note : use form method as get
<?php
if(isset($_GET['id']))
{
call your function here
}
?>
in function access all values using $_GET['fieldname']
simple way make your "Submit " and "Update" action performed on same page then
if(isset($_POST['update']))
{
//perform update task
update($var1,var2,$etc); // pass variables to function
header('Location: http://www.example.com/');// link to your form
}
else if(isset($_POST['submit']))
{
//perform update task
submit($var1,$var2,$etc);// pass variables to function
header('Location: http://www.example.com/'); // link to next page after submit successfully
}
else
{
// display form
}

Categories