Images not displaying - Bad file descriptor - php

This page works for showing everything but the images, which are stored in the public/uploads folder with filenames as "1.jpg", "2.jpg" etc. I seem to be unable to construct a query string that effectively retrieves the image. Need be, I can include the SQLite.
<?php
$page_name = 'gallery';
$nav_plantgallery_class = 'active_page';
// plant gallery requires login to access content
// if (is_user_logged_in()) {
// --- Upload Document ---
// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
define("MAX_FILE_SIZE", 1000000);
// feedback CSS classes
$file_feedback_class = 'hidden';
// $name_feedback_class = 'hidden';
$desc_feedback_class = 'hidden';
$name_feedback_class = 'hidden';
$genus_feedback_class= 'hidden';
// $desc_feedback_class = 'hidden';
$type_feedback_class = 'hidden';
$id_feedback_class='hidden';
// upload fields
$upload_name = NULL;
// $plant_name=
$upload_desc = NULL;
// $upload_source = NULL;
$upload_filename = NULL;
$upload_ext = NULL;
$upload_genus=
$upload_type=
$upload_plantid=NULL;
// sticky values
// Note: file uploads are not sticky!
// $sticky_name = '';
// $sticky_desc = '';
// $sticky_source = '';
$sticky_name = $sticky_genus=
$sticky_desc ='';
$sticky_plantid=
$sticky_planttype_groundcover = '';
$sticky_planttype_fern = '';
$sticky_planttype_flower = '';
$sticky_planttype_shrub = '';
$sticky_planttype_vine = '';
$sticky_planttype_tree = '';
$sticky_planttype_grass = '';
// Users must be logged in to upload files!
if (isset($_POST["upload"])) {
$upload_name = trim($_POST['name']); // untrusted
$upload_desc = trim($_POST['desc']); // untrusted
// $upload_source = trim($_POST['source']); // untrusted
$upload_genus= trim($_POST['genus']);
$upload_type= trim($_POST['type']);
$upload_plantid= trim($_POST['plant_id']);
// get the info about the uploaded files.
$upload = $_FILES['jpg-file'];
// Assume the form is valid...
$form_valid = True;
// file is required
if ($upload['error'] == UPLOAD_ERR_OK) {
// The upload was successful!
// Get the name of the uploaded file without any path
$upload_filename = basename($upload['name']);
// Get the file extension of the uploaded file and convert to lowercase for consistency in DB
$upload_ext = strtolower(pathinfo($upload_filename, PATHINFO_EXTENSION));
// This site only accepts JPG files!
if (!in_array($upload_ext, array('jpg'))) {
$form_valid = False;
}
} else {
// upload was not successful
$form_valid = False;
}
// name is required
if (empty($upload_name)) {
$form_valid = False;
$name_feedback_class = '';
}
// description is required
if (empty($upload_desc)) {
$form_valid = False;
$desc_feedback_class = '';
}
if (empty($upload_genus)) {
$form_valid = False;
$genus_feedback_class = '';
}
if (empty($upload_type)) {
$form_valid = False;
$type_feedback_class = '';
}
if (empty($upload_plantid)) {
$form_valid = False;
$id_feedback_class = '';
}
// // Record NULL (not empty string)
// if (empty($upload_source)) {
// $upload_source = NULL;
// }
if ($form_valid) {
// insert upload into DB
$result = exec_sql_query(
$db,
"INSERT INTO plants (plant_id, name, description, genus, type, file_name, file_ext) VALUES (:plant_id, :name, :description, :genus, :type, :file_name, :file_ext)",
array(
// ':user_id' => $current_user['id'],
':plant_id' => $upload_plantid,
':name' => $upload_name,
':description' => $upload_desc,
':genus' => $upload_genus,
':type' => $upload_type,
':file_name' => $upload_filename,
':file_ext' => $upload_ext,
// ':source' => $upload_source
)
);
if ($result) {
// We successfully inserted the record into the database, now we need to
// move the uploaded file to it's final resting place: public/uploads directory
// get the newly inserted record's id
$record_id = $db->lastInsertId('id');
// uploaded file should be in folder with same name as table with the primary key as the filename.
// Note: THIS IS NOT A URL; this is a FILE PATH on the server!
// Do NOT include / at the beginning of the path; path should be a relative path.
// NO: /public/...
// YES: public/...
$id_filename = 'public/uploads/documents/' . $record_id . '.' . $upload_ext;
// Move the file to the public/uploads/documents folder
// Note: THIS FUNCTION REQUIRES A PATH. NOT A URL!
move_uploaded_file($upload["tmp_name"], $id_filename);
}
} else {
// file uploads are not sticky!
// user must reselect file, show file feedback when showing feedback!
$file_feedback_class = '';
$sticky_name = $upload_name;
$sticky_desc = $upload_desc;
$sticky_genus= $upload_genus;
$sticky_type= $upload_type;
$sticky_plantid=$upload_plantid;
// $sticky_source = $upload_source;
}
}
// --- Document Records ---
// query the database for the grade records
$records = exec_sql_query(
$db,
"SELECT * FROM plants ORDER BY file_name ASC;",
)->fetchAll();
// }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<name><?php echo $page_name; ?> - plants</name>
<link rel="stylesheet" type="text/css" href="/public/styles/site.css" media="all" />
</head>
<body>
<?php include('includes/header.php'); ?>
<main class="plantgallery">
<section class="gallery">
<h2><?php echo $page_name; ?></h2>
<?php
// if (is_user_logged_in()) {
// Only show the documents gallery if we have records to display.
if (count($records) > 0) { ?>
<ul>
<?php
foreach ($records as $record) { ?>
<li>
<a href="/document?<?php echo http_build_query(array('id' => $record['id'])); ?>">
<img class="flower" src="/public/uploads/<?php echo $record['id'] . '.' . $record['file_ext']; ?>" alt="<?php echo htmlspecialchars($record['id']); ?>" />
<p><?php echo ucfirst($record['plant_name']); ?></p>
</a>
</li>
<?php
} ?>
</ul>
<?php
} else { ?>
<p>Gallery is <em>empty</em>.</p>
<?php } ?>
<?php if ($is_admin() && is_user_logged_in()) {?>
<section class="upload">
<h2>Upload Plant</h2>
<form action="/" method="post" enctype="multipart/form-data" novalidate>
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<p class="feedback <?php echo $file_feedback_class; ?>">Please select an JPG file.</p>
<div class="label-input">
<label for="upload-file">JPG File:</label>
<input id="upload-file" type="file" name="jpg-file" accept=".jpg,image/jpg" />
</div>
<p class="feedback <?php echo $name_feedback_class; ?>">Please provide a name.</p>
<div class="label-input">
<label for="upload-name">Plant name:</label>
<input id='upload-name' type="text" name="name" placeholder="plant name" value="<?php echo htmlspecialchars($sticky_name); ?>" />
</div>
<p class="feedback <?php echo $desc_feedback_class; ?>">Please provide a description.</p>
<div class="label-input">
<label for="upload-desc">Description:</label>
<textarea id="upload-desc" name="desc" rows="5" placeholder="plant description."><?php echo htmlspecialchars($sticky_desc); ?></textarea>
</div>
<p class="feedback <?php echo $genus_feedback_class; ?>">Please provide a genus.</p>
<div class="label-input">
<label for="upload-genus">Genus:</label>
<input id='upload-genus' type="text" name="genus" placeholder="plant genus" value="<?php echo htmlspecialchars($sticky_genus); ?>" />
</div>
<p class="feedback <?php echo $id_feedback_class; ?>">Please provide a plant ID.</p>
<div class="label-input">
<label for="upload-id">name:</label>
<input id='upload-id' type="text" name="id" placeholder="plant id" value="<?php echo htmlspecialchars($sticky_plantid); ?>" />
</div>
<!-- <div class="label-input">
<label for="upload-source" class="optional">Source URL:</label>
<input id='upload-source' type="url" name="source" placeholder="URL where found. (optional)" value="<?//php echo htmlspecialchars($sticky_source); ?>" />
</div> -->
<div class="align-right">
<button type="submit" name="upload">Upload Plant</button>
</div>
</form>
</section>
<?php
// } else {
?>
<!-- <p>Please login to access your plant gallery.</p> -->
<?php
//echo_login_form('/', $session_messages);
?>
<?php
}
?>
</main>
<?//php include("includes/footer.php"); ?>
</body>
</html>

You save your files into public/uploads/documents/ but take from different folder public/uploads/. Try to fix the src path like this
<?php
foreach ($records as $record) { ?>
<li>
<a href="/document?<?php echo http_build_query(array('id' => $record['id'])); ?>">
<img class="flower" src="/public/uploads/documents/<?php echo $record['id'] . '.' . $record['file_ext']; ?>" alt="<?php echo htmlspecialchars($record['id']); ?>" />
<p><?php echo ucfirst($record['plant_name']); ?></p>
</a>
</li>
<?php
} ?>

Related

File (image) Upload issue in codeigniter

Actually, I have saved all the data in database after i have show in front end,in my side issue is i have created upload image function to save database after i fetch and display the front end,upload function is taking to save full path like :C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg. all the images saved folder also but in front end is coming like this only : C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg please i need save database like this : (images/media/rajkumar-1499778784/19510.jpg) please help me how will resolve this this is my first sit is codeigniter please help how will pass like this url.
Here my code for controller:
function addNewMedia()
{
if($this->isAdmin() == TRUE)
{
$this->loadThis();
}
else
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('event_image','Pg Image');
// $this->form_validation->set_rules('media_image','Image');
// $this->form_validation->set_rules('date_added','Date','trim|required');
if($this->form_validation->run() == FALSE)
{
$this->addNew();
}
else
{
$data = array(); $upload_data = array();
$this->load->library('upload');
$data['name'] = $this->input->post('name');
$folder_srting = $data['name']."-".time();
$data['name'] = $this->input->post('name');
// print_r($folder_srting);
$folder_string = str_replace(' ', '-', $folder_srting);// Replaces all spaces with hyphens.
$folder_string = preg_replace('/[^A-Za-z0-9\-]/', '', $folder_srting);// Removes special chars.
$folder_name = preg_replace('/-+/', '-', strtolower($folder_string));// Replaces multiple hyphens with single one.
print_r($folder_name);
//$data['name'] = $this->input->post('name');
//$pg_id = $this->input->post('pg_id');
if ($_FILES['event_image']['error'] != 4)
{
$folder = $this->checkdirectory($folder_name);
//print_r($folder_name);
$this->upload->initialize($this->set_upload_options($folder));
if ( ! $this->upload->do_upload('event_image'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error); die;
}
else
{
$upload_data['banner_data'] = $this->upload->data();
//print_r($upload_data['banner_data']);die;
$upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path'];
//print_r($upload_data['bannerfilepath']);die;
}
foreach($upload_data['banner_data'] as $bannerfilepath){
$data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']);
//print_r($data['banner_image_path']);die;
}
$event_image = $data['banner_image_path'];
//print_r($event_image);die;
}
// $name = ucwords(strtolower($this->input->post('name')));
$event_image = $event_image;
//print_r($event_image);die;
$name = $this->input->post('name');
$address = $this->input->post('pg_address');
$incharge_name = $this->input->post('pg_incharge_name');
$incharge_mobile = $this->input->post('pg_incharge_mobile');
$email = $this->input->post('pg_email');
$mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$address,'pg_incharge_name'=>$incharge_name,'pg_incharge_mobile'=> $incharge_mobile,'pg_email'=>$email,'folder_name'=>$folder);
//echo "<pre>";print_r($mediaInfo);die;
$this->load->model('media_model');
//echo "<pre>";print_r($mediaInfo);die;
$result = $this->media_model->addNewMedia($mediaInfo);
if($result > 0)
{
$this->session->set_flashdata('success', 'New Pg created successfully');
}
else
{
$this->session->set_flashdata('error', 'Pg creation failed');
}
redirect('mediaListing');
}
}
}
function editMedia()
{
if($this->isAdmin() == TRUE)
{
$this->loadThis();
}
else
{
$this->load->library('form_validation');
$eventId = $this->input->post('pg_id');
$this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('event_image','Pg Image');
//$this->form_validation->set_rules('event_description','Event Description','required|max_length[200]');
// $this->form_validation->set_rules('start_date','Start Date','trim|required');
//$this->form_validation->set_rules('end_date','End Date','trim|required');
//$this->form_validation->set_rules('additional_images','Additional Images');
//$this->form_validation->set_rules('short_description','Short Description','required');
if($this->form_validation->run() == FALSE)
{
$this->editNew($eventId);
}
else
{
$data = array(); $upload_data = array();
$this->load->library('upload');
$existing_folder = $_POST['folder_name'];
//print_r($existing_folder);die;
if(isset($_POST['image_exists']) && $_POST['image_exists']!= '')
$temp_attachment = $_POST['image_exists'];
$folder = $this->checkdirectory($existing_folder);
if (isset($_FILES['event_image']['name']) && $_FILES['event_image']['error'][0] != 4 && $_FILES['event_image']['name']!='') {
$this->upload->initialize($this->set_upload_options($folder));
if ( ! $this->upload->do_upload('event_image'))
{
$error = array('error' => $this->upload->display_errors());
//print_r($error); die;
}
else
{
$upload_data['banner_data'] = $this->upload->data();
$upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path'];
}
// GET REQUIRED BANNER IMAGES FILE PATH FROM FULL PATH
foreach($upload_data['banner_data'] as $bannerfilepath){
$data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']);
print_r($data['banner_image_path']);die;
}
$event_image = $data['banner_image_path'];
//print_r($event_image);die;
}
else{
// echo "sfgjdf";
$event_image = $temp_attachment;
// print_r($event_image);die;
}
$event_image = $event_image;
$name = $this->input->post('name');
$pg_address = $this->input->post('pg_address');
$pg_incharge_name = $this->input->post('pg_incharge_name');
$pg_incharge_mobile = $this->input->post('pg_incharge_mobile');
$pg_email = $this->input->post('pg_email');
// $additional_images = $additional_images;
$mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$pg_address,'pg_incharge_name'=>$pg_incharge_name,'pg_incharge_mobile'=>$pg_incharge_mobile,'pg_email'=>$pg_email,'folder_name'=>$folder);
//echo "<pre>";print_r($mediaInfo);die;
$result = $this->media_model->editMedia($mediaInfo, $eventId);
if($result == true)
{
$this->session->set_flashdata('success', 'Pg updated successfully');
}
else
{
$this->session->set_flashdata('error', 'Pg updation failed');
}
redirect('mediaListing');
}
}
}
here my model:
function addNewMedia($mediaInfo)
{
$this->db->trans_start();
$this->db->insert('tbl_master_property', $mediaInfo);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();
return $insert_id;
}
function getMediaInfo($eventId)
{
$this->db->select('pg_id, name,event_image,pg_address,pg_incharge_name,pg_incharge_mobile,pg_email,folder_name');
$this->db->from('tbl_master_property');
$this->db->where('status', 0);
$this->db->where('pg_id', $eventId);
$query = $this->db->get();
return $query->result();
}
function editMedia($mediaInfo, $eventId)
{
$this->db->where('pg_id', $eventId);
$this->db->update('tbl_master_property', $mediaInfo);
return TRUE;
}
here my view file code:
<?php
define("IMAGE_PATH", "http://localhost/rentozy/admin/");
$eventId = '';
$name = '';
$pg_address = '';
$pg_incharge_name = '';
$pg_incharge_mobile = '';
$pg_email ='';
$event_image = '';
$folder_name = '';
if(!empty($mediaInfo))
{
foreach ($mediaInfo as $ef)
{
$eventId = $ef->pg_id;
$name = $ef->name;
$pg_address = $ef->pg_address;
$pg_incharge_name = $ef->pg_incharge_name;
$pg_incharge_mobile = $ef->pg_incharge_mobile;
$pg_email = $ef->pg_email;
$event_image = $ef->event_image;
$folder_name = $ef->folder_name;
}
}
?>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script> <script type="text/javascript">
//<![CDATA[
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
//]]>
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<i class="fa fa-users"></i> Property Management
<small>Add / Edit Property</small>
</h1>
</section>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Enter Property Details</h3>
</div><!-- /.box-header -->
<!-- form start -->
<form role="form" action="<?php echo base_url() ?>editMedia" method="post" id="editEvent" role="form" enctype="multipart/form-data" files="true">
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="event_name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name" value="<?php echo $name; ?>" maxlength="128" readonly>
<input type="hidden" value="<?php echo $eventId; ?>" name="pg_id" id="eventId" />
<input type="hidden" value="<?php echo $folder_name; ?>" name="folder_name"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6" style="padding-bottom:15px;">
<div class="form-group">
<label for="description" class="pull-left">Pg Address</label>
<textarea rows="6" cols="50" name="pg_address" class="pull-left" style="width:100%;" value="<?php echo $pg_address;?>" id="pgaddress"><?php echo $pg_address;?></textarea>
</div>
</div>
<div class="col-md-6" style="padding-bottom:15px;">
<div class="form-group">
<label for="description" class="pull-left">Pg Incharge Name</label>
<div class="clearfix"></div>
<textarea rows="6" cols="50" name="pg_incharge_name" class="pull-left" style="width:100%;" value="<?php echo $pg_incharge_name;?>" id="pg_incharge_name" ><?php echo $pg_incharge_name;?></textarea>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="start-date">Pg Incharge Mobile</label>
<input type="text" class="form-control required pg_incharge_mobile" value="<?php echo $pg_incharge_mobile;?>" id="pg_incharge_mobile" name="pg_incharge_mobile">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="end-date">Pg Email</label>
<input type="text" class="form-control pg_email" value="<?php echo $pg_email;?>" id="pg_email" name="pg_email">
</div>
<div class="col-md-6">
<div class="col-md-6">
<div class="form-group">
<label for="event_image">Pg Image</label>
<input type="file" value="<?php echo $event_image; ?>" class="form-control file_change1" id="eventimage" name="event_image">
<img src="<?php echo IMAGE_PATH.$event_image;?>" width="100px" height="50px">
<input type="hidden" name="image_exists" value="<?php echo $event_image;?>" class="form-control" id="eventimage" placeholder="Enter Image Text" aria-describedby="fileHelp">
<div><?php echo $event_image;?></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I don't know if you've thought about it, but you could easily use PHP's str_replace to do what you need.
<?php
$path = $upload_data['banner_data']['full_path'];
$dir = 'C:/xampp/www/htdocs/rentozy/admin/';
$url = str_replace( $dir, '', $path );
echo $url;
In CodeIgniter, if you are saving to a path that is a directory off of document root, you can use the FCPATH constant to make this easy. So if your path to your upload folder is in a directory named /uploads/, and /uploads/ is at document root, then:
<?php
$path = $upload_data['banner_data']['full_path'];
$dir = FCPATH . 'uploads/';
$url = str_replace( $dir, '', $path );
echo $url;
This is just an example, but it is easy

Carrying a variable via session to another file

I have searched through numerous posts on this site to figure out why my session variable is not being recognized, but I haven't been able to figure out a solution.
It is really simply what I am trying to do. I have two PHP files. The first one I have the following code. I HAVE started a session.
PHP file 1
$profile_viewer = $_GET['user'];
$_SESSION['viewer'] = $profile_viewer;
PHP file 2
$_SESSION['viewer'] = $profile_viewer;
I keep getting the error : Notice: Undefined variable: profile_viewer
What am I doing wrong with putting $profile_viewer in the session and then calling for it?
EDIT:
File 1
$profile_user = $_GET['user'];
$_SESSION['viewer'] = $profile_user;
File 2
$user = new User();
//$profile_user = $_GET['user'];
$profile_user = $_SESSION['viewer'];
echo $profile_user;
$friend_status = $_POST['friend_status'];
$okay = true;
if ( $okay ) {
$add_friend_sql = "
INSERT INTO friends
(friend_one, friend_two, date)
VALUES(?, ?, NOW())
";
$add_friend_stmt = $con->prepare($add_friend_sql);
$add_friend_stmt->execute(array($user_id, $profile_user));
}
Full code for file 1
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once '../core/init_account.php';
if(Session::exists('home')) {
echo '<p>' . Session::flash('home') . '</p>';
}
if(!$user->isLoggedIn()) {
Redirect::to('../index');
}
$profile_user = $_GET['user'];
$_SESSION['viewer'] = $profile_user;
// If you make a file function, you can change where things are saved
// You can also change the destination (for portability)
function UploadFile($fileArray = array(), $destinationFolder = 'profile_images/') {
$filename = $fileArray['file']['name'];
$tmp_name = $fileArray['file']['tmp_name'];
$filesize = $fileArray['file']['size'];
$file_error = $fileArray['file']['error'];
$file = $fileArray['file'];
// Save all the default data.
// Success and error should be set by default to fail
$return['error'] = true;
$return['success'] = false;
$return['file']['dest'] = $destinationFolder.$filename;
$return['file']['size'] = $filesize;
if($file_error == 0)
$return['error'] = false;
// I added a directory creation function so you don't have to
// manually make folders. This will do it for you.
if(!is_dir($destinationFolder))
mkdir($destinationFolder,0755,true);
// If your filename is not empty, return success or fail of upload
if (!empty($filename))
$return['success'] = (move_uploaded_file($tmp_name, $destinationFolder.$filename));
return $return;
}
// Create a save-to-database function so it's easier and reusable
function SaveToDb($con,$filename = false) {
// Return fail immediately if the connection is false or image is invalid
if(empty($filename) || !$con)
return false;
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$img_insert_sql = "
INSERT INTO profile_img
(user_id, img)
VALUES (?, ?)
";
if($img_insert_stmt = $con->prepare($img_insert_sql)) {
$img_insert_stmt->execute(array($user_id, $filename));
return true;
}
return false;
}
// Get current profile img
function getPhoto($con) {
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$profile_viewer = $_GET['user'];
if ($profile_viewer == $user_id) {
/*$img_select_sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC
LIMIT 1
";*/
$img_select_sql = "
SELECT i.*
FROM profile_img i
WHERE user_id IN (?, ?)
ORDER BY id DESC
LIMIT 1;
";
}
else {
//echo "This is not your image";
echo $profile_viewer;
$img_select_sql = "
SELECT i.*
FROM profile_img i
WHERE user_id IN (?, ?)
ORDER BY id DESC
LIMIT 1;
";
}
if ($select_img_stmt = $con->prepare($img_select_sql)) {
$select_img_stmt->execute(array($user_id, $profile_user));
$rows = $select_img_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
//$status = $row['status'];
return $row;
}
}
}
// Make sure all functions above are include here. Checks for post
if(isset($_POST['create'])) {
// Try uploading
$upload = UploadFile($_FILES);
// If upload fails
if(!$upload['success']) {
echo '<h3>Sorry, an error occurred</h3>';
}
else {
// You could add error handling here based on the results of
// each function's success or failure below.
// Try to save it
$saveToDb = SaveToDb($con,$upload['file']['dest']);
// Get the profile from image name
$profPic = ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;
}
}
$profPic = getPhoto($con);
?>
</head>
<body>
<?php
include_once("../analyticstracking.php");
if($user->hasPermission('User')) {
include 'nav/navUser.php';
}
?>
<div id="main">
<?php
$profile_viewer_message = null;
if($profile_user == $user_id) {
echo $profile_viewer_message = "This is your profile.";
} else {
echo $profile_viewer_message = "You are viewing someone elses profile.";
echo '<div id="add-friend"><img src="../icons/collection/add.png" alt="Add Friend">' . "Add Friend" . '</div>';
}
?>
<div id="profile-pic-container">
<img id="profile-pic" src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" />
<img src="../icons/photo-camera.png" id="change-picture" alt="Profile Picture">
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="upload-profile-pic" name="file" class="file-input">
<div id="profile-pic-change">Change profile pic</div>
</div>
<!-- <img width="300px" height="200px" class="none" id="file" src="#" alt="your image">
<input type="submit" class="none" name="create" value="Upload Profile Picture">
</form> -->
<div id="new-profile-pic-preview">
<div id="pic-preview-container"><img class="none pic-preview total-center" id="file" src="#" alt="your image"></div>
<input type="submit" class="none" name="create" value="Upload Profile Picture">
</form>
<a class="popup-close" data-popup-close="popup-1" href="#">Close</a>
</div>
<!-- <form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="upload-profile-pic" name="file" class="file-input">
<img width="300px" height="200px" class="none" id="file" src="#" alt="your image">
<input type="submit" class="none" name="create" value="Upload Profile Picture">
</form> -->
<form action="profile.php" method="POST">
<div class="field">
<label for="streetline1">First Name</label>
<input type="text" class="inputbar" name="streetline1" value="<?php echo escape($user->data()->firstname); ?>">
</div>
<div class="field">
<label for="streetline2">Last Name</label>
<input type="text" class="inputbar" name="streetline2" value="<?php echo escape($user->data()->lastname); ?>">
</div>
<div class="field">
<label for="city">Email</label>
<input type="text" class="inputbar" name="city" value="<?php echo escape($user->data()->email); ?>">
</div>
<div class="field">
<label for="state">Phone</label>
<input type="text" class="inputbar" name="state" value="<?php echo escape($user->data()->phone); ?>">
</div>
<div class="field">
<label for="zipcode">Phone Network</label>
<input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->network); ?>">
</div>
<div class="field">
<label for="zipcode">Birthday</label>
<input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->birthday); ?>">
</div>
<label for="submit">
<input id="signinButton" name="submit" type="submit" value="Submit">
</label>
</form>
</div>
</body>
</html>
Session class
class Session {
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function get($name) {
return $_SESSION[$name];
}
public static function delete($name) {
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function flash($name, $string = '') {
if(self::exists($name)) {
$session = self::get($name);
self::delete($name);
return $session;
} else {
self::put($name, $string);
}
}
}
The only variables that get carried between scripts are $_SESSION['xxx']. Ordinary variables like $profile_user don't persist. The assignment
$_SESSION['viewer'] = $profile_user;
doesn't make $profile_user get copied, it copies its value into $_SESSION, and you have to pull it out of there in the other script. So script 2 should start with:
session_start();
$profile_user = $_SESSION['viewer'];

Wordpress Custom PHP failing at wpdb object

I am trying to create a form on wordpress that automatically updates a custom table in the database. The form works with the "POST" method and calls the PHP file fine, and any code (such as echos) I enter at the beginning work fine. The problem is every time I try and use the wpdb object, the screen is just white and the code stops. It won't run anything including or past where I call wpdb. I have tried both using insert and get results and neither is working. Also, I am getting absolutely no errors in the console output even though I turned debugging on and everything.
This is my php file (which has a permission value of 755):
<?php
global $wpdb;
error_reporting(E_ALL);
echo "New Plant has been submitted.\n";
$plantname = $_POST["name"];
echo "Before";
$myrows = $wpdb->get_results( "SELECT * FROM wp_users" );
exit( var_dump( $wpdb->last_query ) );
echo " After: " . $myrows;
$wpdb->insert('Plants',array('PlantName' => $plantname),array('%s'));
echo $plantname . " has been submitted.";
?>
</body>
</html>
Also, this is my form:
<form action="cgi-bin/add_plant.php" method="post">
Plant Name: <input name="name" type="text" />
Lowest Ideal Temperature: <input name="IdealTempLow" type="text" />
Highest Ideal Temperature: <input name="IdealTempHigh" type="text" />
Lowest Ideal pH: <input name="IdealpHLow" type="text" />
Highest Ideal pH: <input name="IdealpHHigh" type="text" />
Lowest Ideal Humidity Level: <input name="IdealHumLow" type="text" />
Highest Ideal Humidity Level: <input name="IdealHumHigh" type="text" />
Lowest Ideal Moisture Level: <input name="IdealMoistLow" type="text" />
Highest Ideal Moisture Level: <input name="IdealMoistHigh" type="text" />
<input type="submit" />
</form>
By the way, I know I need to sanitize my code, but for right now I just want to be able to get it to work in the first place. I know that nothing is getting added because I logged in to PHPMyAdmin and there is nothing in the table. I also tried getting results from the standard wp tables, but that failed as well.
Edit 1
I have moved everything into a custom template file. I had gotten it working with the separate php file, but I moved it so that I could do form validation and everything all without switching pages. However, now I am having the same error. I had used "require_once" to include wp-load.php in the original and it worked, however now wpdb is still failing and I can't figure out how to include wp-load without it also failing. Originally loading up the page works: I can submit the form however on submit the page fails.
<?php
require_once(ABSPATH . '/wp-config.php');
require_once(ABSPATH . '/wp-load.php');
?>
<?php global $asteria;?>
<?php
get_header();
?>
<?php global $wpdb;?>
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function selfURL()
{
$ret = substr(strtolower($_SERVER['SERVER_PROTOCOL']),0,strpos( strtolower($_SERVER['SERVER_PROTOCOL' ]), "/") );
$ret .= ( empty($_SERVER['HTTPS']) ? NULL : ( ($_SERVER['HTTPS'] == "on") ? "s" : NULL) );
$ret .= "://" . $_SERVER['SERVER_NAME'];
$ret .= ( $_SERVER['SERVER_PORT'] == 80 ? "" : ":".$_SERVER['SERVER_PORT'] );
$ret .= $_SERVER['REQUEST_URI'];
return $ret;
}
function submitPlant($a, $b, $c, $d, $e, $f, $g, $h, $i)
{
$wpdb->show_errors();
// $wpdb->replace('Plants',
// array(
// 'PlantName' => $a,
// 'IdealTempLow' => $b,
// 'IdealTempHigh' => $c,
// 'IdealPHLow' => $d,
// 'IdealPHHigh' => $e,
// 'IdealHumidityLow' => $f,
// 'IdealHumidityHigh' => $g,
// 'IdealMoistureLow' => $h,
// 'IdealMoistureHigh' => $i
// ),
// array(
// '%s',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f'
// )
// );
// $a = $wpdb->insert_id;
// if ($a == false) {
// $SubmitMsg = "Plant entry failed. Please contact system admin.";
// echo "Error: " . $wpdb->print_error();
// } else {
$SubmitMsg = "New Plant has been submitted.";
// }
return $SubmitMsg;
}
... Validation Functions...
?>
<?php
$PlantName = $IdealTempLow = $IdealTempHigh = $IdealpHLow = $IdealpHHigh = $IdealHumLow = $IdealHumHigh = $IdealMoistLow = $IdealMoistHigh = "";
$NameErr = $LTempErr = $HTempErr = $LpHErr = $HpHErr = $LHumErr = $HHumErr = $LMoistErr = $HMoistErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$SubmitMsg = "";
...Form Validation...
if (($NameErr == "") && ($LTempErr == "") && ($HTempErr == "") && ($LpHErr == "") && ($HpHErr == "") && ($LHumErr == "") && ($HHumErr == "") && ($LMoistErr == "") && ($HMoistErr == ""))
{
$SubmitMsg = submitPlant($PlantName, $IdealTempLow, $IdealTempHigh, $IdealpHLow, $IdealpHHigh, $IdealHumLow, $IdealHumHigh, $IdealMoistLow, $IdealMoistHigh);
}
}
?>
<!--Content-->
<div class="fixed_site">
<div class="fixed_wrap singlefx">
<?php if(($asteria['page_type_id']) == '1'){ ?>
<div class="page_tt">
<div class="center"><h1 class="postitle"><?php the_title(); ?></h1></div>
</div>
<?php } ?>
<div id="content">
<div class="center">
<div class="single_wrap no_sidebar">
<div class="single_post">
<?php if(have_posts()): ?>
<?php while(have_posts()): ?><?php the_post(); ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<?php if ( is_user_logged_in() || is_admin() ) { ?><div class="edit_wrap"><i title="<?php _e('Edit This','asteria'); ?>" class="fa-edit"></i></div><?php } ?>
<div class="single_post_content">
<?php if(($asteria['page_type_id']) == '2'){ ?><h1 class="postitle"><?php the_title(); ?></h1><?php } ?>
<div class="thn_post_wrap"><?php the_content(); ?> </div>
<div style="clear:both"></div>
<div class="thn_post_wrap"><?php wp_link_pages('<p class="pages"><strong>'.__('Pages:').'</strong> ', '</p>', 'number'); ?></div>
</div>
</div>
<?php endwhile ?>
</div>
<?php endif ?>
<span style="color:blue"><?php echo $SubmitMsg;?></span>
<form action="<?php echo selfURL(); ?>" method="POST">
Plant Name: <input name="PlantName" type="text" value="<?php echo $PlantName;?>"/><span style="color:red"> * <?php echo $NameErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Temperature: <input name="IdealTempLow" type="text" value="<?php echo $IdealTempLow;?>"/><span style="color:red"> * <?php echo $LTempErr;?></span>
</br><div height="5"> </div>
Highest Ideal Temperature: <input name="IdealTempHigh" type="text" value="<?php echo $IdealTempHigh;?>"/><span style="color:red"> * <?php echo $HTempErr;?></span>
</br><div height="5"> </div>
Lowest Ideal pH: <input name="IdealpHLow" type="text" value="<?php echo $IdealpHLow;?>"/><span style="color:red"> * <?php echo $LpHErr;?></span>
</br><div height="5"> </div>
Highest Ideal pH: <input name="IdealpHHigh" type="text" value="<?php echo $IdealpHHigh;?>"/><span style="color:red"> * <?php echo $HpHErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Humidity Level: <input name="IdealHumLow" type="text" value="<?php echo $IdealHumLow;?>"/><span style="color:red"> * <?php echo $LHumErr;?></span>
</br><div height="5"> </div>
Highest Ideal Humidity Level: <input name="IdealHumHigh" type="text" value="<?php echo $IdealHumHigh;?>"/><span style="color:red"> * <?php echo $HHumErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Moisture Level: <input name="IdealMoistLow" type="text" value="<?php echo $IdealMoistLow;?>"/><span style="color:red"> * <?php echo $LMoistErr;?></span>
</br><div height="5"> </div>
Highest Ideal Moisture Level: <input name="IdealMoistHigh" type="text" value="<?php echo $IdealMoistHigh;?>"/><span style="color:red"> * <?php echo $HMoistErr;?></span>
</br><div height="5"> </div>
<input type="submit" name="submitted"/>
</form>
</div>
<!--PAGE END-->
</div>
</div>
</div>
</div>
<?php get_footer(); ?>

Updation not working using pdo in php

I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];

Checking if the input name and telephone number valid with php

I have tried this code to add validation when the input is name and number. But, there is something wrong with this code. The validation for nama and telepon are always wrong. I use the form and validation in one page.Can you help me solve this problem
<?php
error_reporting(E_ALL);
class ValidateInfo
{
public $errors;
public $message;
public $data;
public $wrong;
public $wrongmessage;
public function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
{
$trimmed = trim($payload[$type]);
if(!empty($validate)) {
// Strip out all but numbers
if(in_array('digits',$validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {
// not an integer!
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Telephon number must be in number';
} else {
$this->wrong[$type] = 0;
}
}
// Strip out letters
elseif(in_array('letters',$validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === true) {
// not an integer!
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Name must be in alphabet';
} else {
$this->wrong[$type] = 0;
}
}
// Re-assign data type to consolidate
$this->data[$type] = (!isset($this->data[$type]))? $trimmed:$this->data[$type];
// Check if data is an email
if(in_array('email',$validate)) {
if(filter_var($this->data[$type], FILTER_VALIDATE_EMAIL) === false){
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Tulis email seperti: yourname#email.com';
} else {
$this->wrong[$type] = 0;
}
}
// Strip out html tags
if(in_array('strip',$validate)) {
$this->data[$type] = strip_tags($this->data[$type]);
}
}
if(!isset($this->data[$type]))
$this->data[$type] = $trimmed;
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
}
}
// Creat instance of info processor
$info = new ValidateInfo();
// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {
// Checks empty fields
$info->Check($_POST,'nama','Write your name',array('letters'));
$info->Check($_POST,'telepon','Write the phone number',array('digits'));
$info->Check($_POST,'email','Write the email',array('email'));
$info->Check($_POST,'judul','Write the title');
$info->Check($_POST,'konten','Write the content');
if(array_sum($info->errors) == 0 && array_sum($info->wrong) == 0) {
// path and name of the file
$filetxt = 'dataInJson.json';
// Assign stored data
$data = $info->data;
// path and name of the file
$filetxt = 'dataInJson.json';
// to store all form data
$arr_data = array();
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
// appends the array with new form data
$arr_data[] = $data;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "dataInJson.json"
// outputs error message if data cannot be saved
if(file_put_contents('dataInJson.json', $jsondata)) {
$info->errors['success'] = true; ?>
<script type="text/javascript">alert("Data has been submitted");</script>
<?php }
else {
$info->message['general']['put_file'] = 'Tidak dapat menyimpan data di "dataInJson.json"';
}
}
}
else
$info->message['general']['submit'] = 'Form fields not submited'; ?>
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="center">
<h1>Data Buku</h1>
<?php if(isset($info->errors['success'])) { ?>
<h2>Thank you!</h2>
<?php } else { ?>
<p><span class="error">* required field.</span></p>
<?php } ?>
<hr>
<form action="" method="post">
<?php if(isset($info->message['general'])) {
foreach($info->message['general'] as $_error) { ?>
<span class="error">* <?php echo $_error; ?></span><br>
<?php
}
} ?>
<h2>Informasi Pengarang</h2>
<div class="roadie">
<label for="nama">Nama:</label>
<input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value=" <?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
<?php
if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?>
<span class="error">* <?php echo $info->message['nama']; ?></span><?php
}
if(isset($info->wrong['nama']) && $info->wrong['nama'] == 1) { ?>
<span class="error">* <?php echo $info->wrongmessage['nama']; ?></span><br><?php
}?>
</div>
<div class="roadie">
<label for="telepon">Nomor Telepon:</label>
<input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
<?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?><span class="error">* <?php echo $info->message['telepon']; ?></span><?php }
if(isset($info->wrong['telepon']) && $info->wrong['telepon'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['telepon']; ?></span><br><?php } ?>
</div>
<div class="roadie">
<label for="email">e-Mail:</label>
<input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
<?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?><span class="error">* <?php echo $info->message['email']; ?></span><br><?php }
if(isset($info->wrong['email']) && $info->wrong['email'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['email']; ?></span><br><?php }
?>
</div>
<div class="roadie">
<h2>Tulisan</h2>
<label for="judul">Judul:</label>
<input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
<?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?><span class="error">* <?php echo $info->message['judul']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="konten">Konten:</label>
<textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) { echo strip_tags($info->data['konten']); } ?></textarea>
<?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?><span class="error">* <?php echo $info->message['konten']; ?></span><br><?php } ?>
</div>
<input type="submit" id="submit" name = submit value="Create" />
<input type="reset" id="reset" value="Reset" />
</form>
I debugged your code, and the problem is:
When your program checks your nama field, it has option array('letters') for $validate.
elseif (in_array('letters', $validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {
So when you want to check letters, why do you use FILTER_VALIDATE_INT ?
The other problem is here:
if(!isset($this->data[$type])) {
$this->data[$type] = $trimmed;
}
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
This block is at the end of your Check. So, when first run, you try to check an empty thing, and then when method finishes, the nama will be added to the $this->data. This is why your second Check call does not found the telpone. So move this block to the top of your method, and validate, is this exists. Validate formats only after this check.

Categories