I am using Codeigniter and I have created a code that checks if there is the same entry already in the database. but i dont know how i will output the error message. the boolean is not working.
VIEW
<h8><b>Add New Service: For single upload. <?php echo $status; ?></b></h8><hr>
<form action="<?php echo base_url(); ?>some_controller/insertServ" method="post">
<center>Service Name: <input type="text" name="ci_name"/>
<input type="submit" class="classname" value="Save"/></center>
</form>
CONTROLLER
public function insertServ(){
/* logic behind adding a new service
*/
$ci_name = $this->input->post('ci_name');
$success = $this->some_model->addCI($ci_name);
if($success == TRUE)
$this->viewMap_add(TRUE);
else $this->viewMap_add(FALSE);
}
public function viewMap_add($success = NULL){
/* Shows the list of the services with a dialog box for
* adding a new service
*/
if($success == NULL)
$status = 'N/A';
else if($success == TRUE)
$status = 'Success';
else $status = 'FAILED';
$data['status'] = $status;
$data['current_user']=$this->session->userdata('email');
$data['mapList'] = $this->some_model->getMapped();
$this->load->view('templates/header.php',$data);
$this->load->view('some_page/servList_add.php',$data);
}
MODEL
public function addCI($ci_name){
/* Adds a new service
*/
$ci_name = $this->db->escape_str($ci_name);
$queryStr = "Select service from appwarehouse.service where service = '$ci_name'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
echo "result already exists";
}
else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$ci_name');";
$query = $this->db->query($queryStr);}
}
First off, your model method addCI isn't returning anything. Fix that.
Then, you can avoid all the mess by simply removing one layer of code and sending the status value directly:
public function insertServ:
if($success)
$this->viewMap_add('Success');
else
$this->viewMap_add('FAILED');
And then just remove all the if-elses in the viewMap_add method.
Also, since you didn't tell exactly what is the problem, try doing the var_dump on the status variable in insertServ or just:
var_dump($this->some_model->addCI($ci_name));
UPDATE
Here is how your model method should look like (nothing to echo there, but return a boolean):
public function addCI($ci_name){
/* Adds a new service
*/
$ci_name = $this->db->escape_str($ci_name);
$queryStr = "Select service from appwarehouse.service where service = '$ci_name'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
return false; // <---- this one is important
}
else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$ci_name');";
$query = $this->db->query($queryStr);
return true; // <---- and this one
}
}
Related
In my Authentication.php class I hava a code like below;
public function prepareTicket($data){
if(array_key_exists('tickettype', $data))
$this->tickettype = $data['tickettype'];
if(array_key_exists('ticketinfo', $data))
$this->ticketinfo = $data['ticketinfo'];
}
function createTicket(){
$sql = "INSERT INTO ticket_test (tickettype, ticketinfo) VALUES ('$this->tickettype','$this->ticketinfo')";
$result = mysqli_query($this->DB_CONNECTION,$sql);
}
function createTicketControl(){
$sql = "SELECT * FROM `ticket_test` WHERE tickettype = '".$this->tickettype."'AND ticketinfo ='".$this->ticketinfo."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
if(mysqli_num_rows($result) >0){
return true;
}else{
return false;
}
}
and in the other php file I have a code like this;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepareTicket($_POST);
$ticketStatus = $auth->createTicketControl();
if($ticketStatus){
$json['success'] = 1;
$json['message'] = 'Destek kaydı oluşturuldu';
}else{
$json['success'] = 0;
$json['message'] = 'Error!';
}
echo json_encode($json);
Now my problem is that whenever I try to insert data to my database it returns 'success' = '0' , 'message' = 'Error' and the data couldnt be inserted on the database.I mean the service is not working properly.Any help is appreciated...
P.S.= I am aware of sql injection threat on this code bu it is for android app so no need to worry about it.
Found the solution.I realised that in CreateTicket.php I didint call createTicket function from Authentication.php :/
I searched before writing this question but didn't think I would find a response because my issue is SO specific.
Anyway, I have been following the PHP Beyond the Basics course on Lynda.com by Kevin Skoglund and have run into a snag when it comes to uploading photos to the database (MySQL). This is my first real foray into OOP and have been brought to a stretching halt. I've been looking at my files for a over week trying my best to sort out the issue with no luck.
Oddly I have tried using the exercise files directly on my local machine and I'm getting the same error (with my information like database creds and directory names).
Basically my problem is that when I try to upload a photo it gets moved from the temp directory to the images directory but never makes its way to the database. I get the 'database query failed' message when it posts and the photograph table in mysql remains empty. I see where the error is coming from ( inside database.php confirm_query() ) but have no inclination as to what the issue could be. I know I am able to communicate with the database because just before moving onto creating the photograph class/table I was able to add users to the user table in the database.
Below are my files. Im adding the three that I believe relate to this issue but will zip the whole project up and upload it to dropbox as well. Any help/insight would be more than greatly appreciated!!
*please note that I have put the functions from the databaseObject into the photograph class
photo_upload.php:
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) {
redirect_to("login.php");
}
$max_file_size = 1048576; //expressed in bytes
// 10240 = 10kb
// 102400 = 100kb
//1048576 = 1mb
//10485760 = 1mb
$message = "";
if (isset($_POST['submit'])) {
$photo = new Photograph();
$photo->caption = $_POST['caption'];
$photo->attach_file($_FILES['file_upload']);
if ($photo->save()) {
//success
$message = "Photograph uploaded successfully";
} else {
//failure
$message = join("<br>", $photo->errors);
}
}
include_layout_template('admin_header.php');
?>
<h2>Photo Upload</h2>
<?php echo output_message($message); ?>
<form action="photo_upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>">
<p><input type="file" name="file_upload"></p>
<p>Caption: <input type="text" name="caption" value=""></p>
<input type="submit" name="submit" value="upload">
</form>
<?php include_layout_template('admin_footer.php'); ?>
Photograph.php:
<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class Photograph extends DatabaseObject {
protected static $table_name="photographs";
protected static $db_fields=array('id', 'filename', 'type', 'size', 'caption');
public $id;
public $filename;
public $type;
public $size;
public $caption;
private $temp_path;
protected $upload_dir="images";
public $errors=array();
protected $upload_errors = array(
// http://www.php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
// Pass in $_FILE(['uploaded_file']) as an argument
public function attach_file($file) {
// Perform error checking on the form parameters
if(!$file || empty($file) || !is_array($file)) {
// error: nothing uploaded or wrong argument usage
$this->errors[] = "No file was uploaded.";
return false;
} elseif($file['error'] != 0) {
// error: report what PHP says went wrong
$this->errors[] = $this->upload_errors[$file['error']];
return false;
} else {
// Set object attributes to the form parameters.
$this->temp_path = $file['tmp_name'];
$this->filename = basename($file['name']);
$this->type = $file['type'];
$this->size = $file['size'];
// Don't worry about saving anything to the database yet.
return true;
}
}
public function save() {
// A new record won't have an id yet.
if(isset($this->id)) {
// Really just to update the caption
$this->update();
} else {
// Make sure there are no errors
// Can't save if there are pre-existing errors
if(!empty($this->errors)) { return false; }
// Make sure the caption is not too long for the DB
if(strlen($this->caption) > 255) {
$this->errors[] = "The caption can only be 255 characters long.";
return false;
}
// Can't save without filename and temp location
if(empty($this->filename) || empty($this->temp_path)) {
$this->errors[] = "The file location was not available.";
return false;
}
// Determine the target_path
$target_path = SITE_ROOT .DS. 'public' .DS. $this->upload_dir .DS. $this->filename;
// Make sure a file doesn't already exist in the target location
if(file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
// Attempt to move the file
if(move_uploaded_file($this->temp_path, $target_path)) {
// Success
// Save a corresponding entry to the database
if($this->create()) {
// We are done with temp_path, the file isn't there anymore
unset($this->temp_path);
return true;
}
} else {
// File was not moved.
$this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
return false;
}
}
}
// Common Database Methods
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record) {
// Could check that $record exists and is an array
$object = new self;
// Simple, long-form approach:
// $object->id = $record['id'];
// $object->username = $record['username'];
// $object->password = $record['password'];
// $object->first_name = $record['first_name'];
// $object->last_name = $record['last_name'];
// More dynamic, short-form approach:
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
// return an array of attribute names and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
// replaced with a custom save()
// public function save() {
// // A new record won't have an id yet.
// return isset($this->id) ? $this->update() : $this->create();
// }
public function create() {
global $database;
// Don't forget your SQL syntax and good habits:
// - INSERT INTO table (key, key) VALUES ('value', 'value')
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
// Don't forget your SQL syntax and good habits:
// - UPDATE table SET key='value', key='value' WHERE condition
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
public function delete() {
global $database;
// Don't forget your SQL syntax and good habits:
// - DELETE FROM table WHERE condition LIMIT 1
// - escape all values to prevent SQL injection
// - use LIMIT 1
$sql = "DELETE FROM ".self::$table_name;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
// NB: After deleting, the instance of User still
// exists, even though the database entry does not.
// This can be useful, as in:
// echo $user->first_name . " was deleted";
// but, for example, we can't call $user->update()
// after calling $user->delete().
}
}
?>
database.php:
<?php
require_once("config.php");
class MySQLDatabase {
//Step #1 open connection
private $connection;
function __construct() {//once you create an instance of this class it will automatically create the connection
$this->open_connection();
}
public function open_connection(){
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
//Test the connection
if(mysqli_connect_errno()){//use errno because error returns an empty string if succesful
die('Database connection failed: '. mysqli_connect_error().
'('.mysqli_connect_errno().')');
}
}
//Step #2 preform database query
public function query($sql){
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result){
if(!$result){ //this is a check to make sure the query worked
die('Database query failed');
}
}
public function escape_value($string){
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
//database neutral functions
//this is our database adapter which is called for mysql
public function fetch_array($result_set){
return mysqli_fetch_array($result_set);
}
public function num_rows($result_set) {
return mysqli_num_rows($result_set);
}
public function insert_id(){
//get the last id inserted over the current connection
return mysqli_insert_id($this->connection);
}
public function affected_rows(){
return mysqli_affected_rows($this->connection);
}
//Step #4 close connection
public function close_connection() {
if(isset($this->connection)){
mysqli_close($this->connection);
unset($this->connection);
}
}
}
$database = new MySQLDatabase();
?>
https://www.dropbox.com/s/oqdi2dz2mbkuwzz/photo_gallery.zip?dl=0
After more digging around I have concluded that my problem was not with my code. There was an sql setting that would not allow me to enter and empty string sqlmode=STRICT_TRANS_TABLES. Thank you maxhb for pointing me in the right direction!!
What I did end up doing to solve this issue was create a my.conf file to change the default settings (im running mysql 5.7.9 on mac osx 10.11 btw). What was weird was that it only worked if I put this file in two locations they are .my.cnf and /etc/mysql/my.cnf with the following text:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION
I am trying to create a function that will check against the data from the database. If the results are empty, continue with the code. If else, abort.
Here is an example of my code.
function check_if_blocked(){
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(empty($results)){
$var = false;
} else {
$var = true;
}
return $var;
}
Function check_if_blocked is going to be used multiple through out the plugin.
Here is an example of how I plan on using check_if_blocked()..
function msg_form(){
if(check_if_blocked(){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send">';
}
}
Regardless on how I switch around the true, false, and even if(!check_if_blocked...
You are trying to return the wrong value, get_results will return true if the query was successful, not if it found matches, so, it might return true even if there are no matching records found, try this instead:
function check_if_blocked()
{
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(!$results) {return false;} // query failed, no way to know if there are matching records.
$numrows = count($results); // query worked, now, check if there are matching records.
if (is_int($numrows) && $numrows) {$var = true;} else {$var = false;}
return $var; // return the result.
}
Now, the function will return true only if there are one or more matching records.
Also, you have a syntax error here:
if(check_if_blocked(){
It should be:
if(check_if_blocked()){
After everyone's advice. I finally got it to work. Here is my code.
function check_if_blocked($blocked){
global $wpdb;
$user = '1';
$user2 = '2';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE blocked = $user AND blocker = $user2");
if(empty($results)){
$blocked = 'not_blocked';
} else {
$blocked = 'is_blocked';
}
}
function msg_form(){
if(check_if_blocked($blocked) == 'not_blocked){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send"></form>';
}
}
Good day! I'm new to PHP and I'm stuck on this. The problem is, how can I load an specific function from a class into the php file. This is all I got:
HTML FILE
<form action="myfile.php" method="post">
<input type="text" name="subject"/>
<input type="text" name="section"/>
<input type="submit" name="submit"/>
</form>
PHP FILE
<?php
include 'class_lib.php';
$subject = $_POST['subject'];
$section = $_POST['section'];
if(isset($_POST['submit'])){
$class = new myClass;
$success = $class->insertFunction();
if($success == TRUE)
{echo 'Inserted';}
else
{echo 'Error';}
}
?>
FUNCTION FILE
class myClass{
function insertFunction(){
$sql = "Insert into tblName (subject, section) VALUES($subject,$section)";
$success = mysql_query($sql) or die (mysql_error());
return $success;
}
}
The problem is when I submit the button it gives me a blank page. Please help me, i'm new with this so spare with me. Any help is much appreciated.
There are multiple ways to get the values available to the class-function,
lets try the quick fix -
1.
Instead of -
$success = $class->insertFunction();
write
$success = $class->insertFunction($subject, $section); //Pass the parameters
and
class myClass{
function insertFunction($subject, $section){ //Get the parameter values
[....]
}
}
Now check the value of $success. If the query was successfully executed then the value should be the primary key (auto-increment). I hope the database table has such a field.
2.
Now lets do it in the proper way -
Add two properties to the class file -
class myClass{
public $subject;
public $section;
function insertFunction(){
$sql = "Insert into tblName (subject, section) VALUES($this->subject, $this->section)";
return mysql_query($sql);
}
}
Then change the .php file as -
<?php
include 'class_lib.php';
[......] //include your class file.
$subject = $_POST['subject'];
$section = $_POST['section'];
if(isset($_POST['submit'])) {
$class = new myClass;
$class->subject = $subject;
$class->section = $section;
$success = $class->insertFunction();
if($success)
echo 'Inserted';
else
echo 'Error';
}
?>
I hope it gives some idea.
Whenever I add a new place/description in my UI, it will save automatically to my database. My problem is that I can still add a place eventhough it's already existing. All I want is that it won't save/update a new description/place if it's already exist.
Any advice would be much appreciated.
Thanks.
This is my my EditPlaces:
public function executeEditPlaces(sfWebRequest $request)
{
try{
$id = pg_escape_string(strip_tags($request->getParameter("id")));
// $id = $request->getParameter("id");
$query = "select description from country.regions where id = ('$id')";
// die($query);
$result=$this->conn->fetchAll($query);
if(count($result)>0){
$v = $result[0];
$data['data'] = array('description' => $this->formatString($v['description']));
}
$data['success']=true;
$data['msg']=$msg;
die(json_encode($data));
}
catch(exception $e)
{
$data['success']=false;
$data['msg']=$e->getMessage();
die(json_encode($data));
}
}
This is my UpdatePlaces:
public function executeUpdatePlaces(sfWebRequest $request)
{
try{
$by = $_SESSION['employee_id'];
$now = date("Y-m-d H:I:s");
$id = $request->getParameter("id");
$description = pg_escape_string(strip_tags($request->getParameter("description")));
$description = trim($description);
if(strlen($description) == 0)
{
die('cannot be empty');
}
else
{
$query = "update country.regions set description=('$description'),modified_by=('$by'),date_modified=('$now') where id=('$id')";
$msg = "Existing Region Successfully Updated.";
$this->conn->execute($query);
$data['success']=true;
$data['msg']=$msg;
die(json_encode($data));
}
}
catch(exception $e)
{
$data['success']=false;
$data['msg']=$e->getMessage();
die(json_encode($data));
}
}
There is two way:
You can alter your table so the column is unique
ALTER IGNORE TABLE country.regions ADD UNIQUE (description);
Check if your description/place already exist using a select
$query = "select description from country.regions";
$result=$this->conn->fetchAll($query);
if(count($result)>0){
print 'already exist'
} else {
//insert code
}
Please check if $description of duplicated entries are really the same.
You may introduce UNIQUE constraint to SQL schema for the columns that must be unique - it will introduce security in the lower layer.
Please check if description is of type bytea. If yes, pg_escape_bytea should be used instead of pg_escape_string.