I am working in CakePHP. I want to save posted data into my database.So I have created function in controller that looks like below :
function add_news()
{
$this->_checkSession();
$this->layout = "admin_inner";
if(!empty($this->params['form']))
{
$tit = $this->params['form']['title'];
$con = $this->params['form']['content'];
$query = "insert into news(news_title,news_content) values('".$tit."','".$con."')";
echo $query;
$this->News->query($query);
}
Configure::write('debug', '2');
}
I print query and execute in database then it works fine.But here it does not execute.I do not have News model.
Note : I am working in CakePHP 1.3.13
first you need to know how to insert data in cakephp ....link for this is :- http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Models.html
then you can try this code to insert data in table
if(!empty($this->params['form']))
{
$tit = $this->params['form']['title'];
$con = $this->params['form']['content'];
$data = array(
"news_title"=>$tit,
"news_content"=>$con
);
$this->News->save($data);
}
function add_news()
{
$this->_checkSession();
$this->layout = "admin_inner";
if(!empty($this->params['form']))
{
$tit = $this->params['form']['title'];
$con = $this->params['form']['content'];
$data = array(
"news_title"=>$tit,
"news_content"=>$con
);
$this->News->save($data);
}
Configure::write('debug', '2');
}
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 have problem in updating fields in database via codeigniter update method
My controller:
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$user = $this->API_model->get_user($url[0]);
print_r($user);
if ($this->db->update('user', $database , $user['id']) === true) {
print_r($database);
echo "MEI_TRUE";
}else {
echo "MEI_FALSE";
}
browser return MEI_TRUE that mean database successfully updated but when I check database in phpmyadmin nothing changed :(
what 's the problem?
It should work now.
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$user = $this->API_model->get_user($url[0]);
print_r($user);
$query = $this->db->where('id',$user['id'])
->update('user', $database);
if ($query) {
print_r($database);
echo "MEI_TRUE";
}else {
echo "MEI_FALSE";
}
Can you try something like below,
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$this->db->where('id', $user['id']);
$this->db->update('user', $database );
Hope this will help you
the thing is - what do you want to update ?
the 3rd parameter of the update query lets you enable the where clause as a string
although your example is pretty dangerous, try the following
if ($this->db->update('user', $database , "id = ".$user['id']) === true)
{
print_r($database);
echo "MEI_TRUE";
}
else
{
echo "MEI_FALSE";
}
the better way would be (as Dhanesh already mentioned):
$blnUpdateSuccess = $this->db->where("id", $user['id'])->update("user",$database);
if ($blnUpdateSuccess)
{
print_r($database);
echo "MEI_TRUE";
}
else
{
echo "MEI_FALSE";
}
For more information read the Documentation here
I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);
In the below codeigniter code i have placed the controller ,model and view part.My aim is to drop exam name from exam table.In my case it is drop the exam name from exam table.Pls help me o do this .
Controller
public function index()
{
//echo "inside form upload";
$data = array();
//$college_name = $this->session->userdata('college_name');
if($query = $this->import_model->get_exam_data())
{
$data['exam_data'] = $query;
}
//$this->load->view('student_view', $data);
$this->load->view('form_upload');
}
model
function get_exam_data()
{
//$this->db->distinct();
$this->db->select("CONCAT(exam_name, ' ', month,' ',year) AS fullexamname", FALSE);//this will concat the value
//$this->db->where('college_name',$college_name);
$query = $this->db->get('exam_table');
return $query->result();
}
view
<?php
$data = array();
$data["Select Exam Name"] = "Select Exam Name";
foreach ($exam_data as $row)
{
$data[$row->fullexamname] = $row->fullexamname;
}
echo form_dropdown('exam_name', $data, 'small', 'class="dropdown_class" id="exam_name_id" ');
?>
*
You have to pass $data to your view file from controller
$this->load->view('form_upload',$data);
i have a website with a dynamic navigational menu. I keep the controller (portuguese) names in a database, together with the translation to english.
I want to know if it is possible to affect the 'route' array at runtime, so it would create those routes and cache it when the page is loaded.
I hope I was clear enough, thanks for the help
You could do this:
Create a table named Routes
--
-- Table structure for table `Routes`
--
CREATE TABLE IF NOT EXISTS `Routes` (
`idRoutes` int(11) NOT NULL AUTO_INCREMENT,
`Order` int(11) NOT NULL,
`Url` varchar(250) NOT NULL,
`Url_Variable` varchar(20) NOT NULL,
`Class` text NOT NULL,
`Method` text NOT NULL,
`Variable` text NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`idRoutes`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=67 ;
Create a file in the config directory named pdo_db_connect.php
Put this inside and change accordingly.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function pdo_connect(){
try{
// Include database info
include 'database.php';
if(!isset($db)){
echo 'Database connection not available!';
exit;
}
$dbdriver = $db['default']['dbdriver'];//'mysql';
$hostname = $db['default']['hostname'];//'localhost';
$database = $db['default']['database'];//'config';
$username = $db['default']['username'];//'root';
$password = $db['default']['password'];//'password';
//to connect
$DB = new PDO($dbdriver.':host='.$hostname.'; dbname='.$database, $username, $password);
return $DB;
}catch(PDOException $e) {
echo 'Please contact Admin: '.$e->getMessage();
}
}
Now in your routes file you can do this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Include our PDO Connection
include('application/config/pdo_db_connect.php');
class dynamic_route{
public $pdo_db = FALSE;
public function __construct(){
}
private function query_routes(){
try{
$routes_query = $this->pdo_db->query('SELECT * FROM Routes ORDER BY `Order` ASC');
if($routes_query){
$return_data = array();
foreach($routes_query as $row) {
$return_data[] = $row;
}
return $return_data;
}
}catch(PDOException $e) {
echo 'Please contact Admin: '.$e->getMessage();
}
}
private function filter_route_data($data){
$r_data = array();
foreach($data as $row){
$return_data = new stdClass;
if(empty($row['Url_Variable']) ){
$return_data->url = $row['Url'];
}else{
$return_data->url = $row['Url'].'/'.$row['Url_Variable'];
}
if(empty($row['Method']) && empty($row['Variable']) ){
$return_data->route = $row['Class'];
}elseif(!empty($row['Method']) && empty($row['Variable']) ){
$return_data->route = $row['Class'].'/'.$row['Method'];
}elseif(!empty($row['Method']) && !empty($row['Variable']) ){
$return_data->route = $row['Class'].'/'.$row['Method'].'/'.$row['Variable'];
}
$r_data[] = $return_data;
}
return $r_data;
}
public function get_routes(){
$route_data = $this->query_routes();
$return_data = $this->filter_route_data($route_data);
return $return_data;
}
}
$dynamic_route = new dynamic_route;
// Give dynamic route database connection
$dynamic_route->pdo_db = pdo_connect();
// Get the route data
$route_data = $dynamic_route->get_routes();
//Iterate over the routes
foreach($route_data as $row){
$route[$row->url] = $row->route;
}
Remember that the routes file is just a PHP file that contains an array, so if you want to get your "Hacker" t-shirt on you could easily do something a little bit dirty.
Have your CMS/application/web-app/fridge-monitoring-system/whatever to have an interface which creates and stores records in a database. Then whenever you save, throw this content into application/cache/routes.php.
Lastly you just have your main routes.php include the cached version and you're good to go.
Yes you can take a look here:
http://ellislab.com/forums/viewthread/185154/
http://ellislab.com/forums/viewthread/182180/
You need the following.
One controller like this which will save your routes to a file called "routes.php" in the application/cache folder:
public function save_routes()
{
// this simply returns all the pages from my database
$routes = $this->Pages_model->get_all($this->siteid);
// write out the PHP array to the file with help from the file helper
if (!empty($routes)) {
// for every page in the database, get the route using the recursive function - _get_route()
foreach ($routes->result_array() as $route) {
$data[] = '$route["' . $this->_get_route($route['pageid']) . '"] = "' . "pages/index/{$route['pageid']}" . '";';
}
$output = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n";
$output .= implode("\n", $data);
$this->load->helper('file');
write_file(APPPATH . "cache/routes.php", $output);
}
}
Here's the second function you will need. This one and the one prior will both go in your application controller which handles your pages:
// Credit to http://acairns.co.uk for this simple function he shared with me
// this will return our route based on the 'url' field of the database
// it will also check for parent pages for hierarchical urls
private function _get_route($id)
{
// get the page from the db using it's id
$page = $this->Pages_model->get_page($id);
// if this page has a parent, prefix it with the URL of the parent -- RECURSIVE
if ($page["parentid"] != 0)
$prefix = $this->_get_route($page["parentid"]) . "/" . $page['page_name'];
else
$prefix = $page['page_name'];
return $prefix;
}
In your Pages_model you will need something along this line:
function get_page($pageid) {
$this->db->select('*')
->from('pages')
->where('pageid', $pageid);
$query = $this->db->get();
$row = $query->row_array();
$num = $query->num_rows();
if ($num < 1)
{
return NULL;
} else {
return $row;
}
}
And this:
function get_all($siteid) {
$this->db->select('*')
->from('pages')
->where('siteid', $siteid)
->order_by('rank');
;
$query = $this->db->get();
$row = $query->row_array();
$num = $query->num_rows();
if ($num < 1)
{
return NULL;
} else {
return $query;
}
}
Every time a page is created, you'll need to have this line executed so I suggest putting it at the end of the controller after all the dirty work is done:
$this->save_routes();
All this together will make you a sweet routes file that will be constantly updated whenever things change.
Something not overly complex, and it keeps the URLs friendly:
inside of routes.php:
// Routes from the database
require_once (BASEPATH .'database/DB.php');
$db =& DB();
// slug will be something like
// 'this-is-a-post'
// 'this-is-another-post'
$sql = "SELECT id, slug FROM items";
$query = $db->query($sql);
$result = $query->result();
foreach( $result as $row )
{
// first is if multiple pages
$route["$row->slug/(:num)"] = "item/index/$row->id";
$route["$row->slug"] = "item/index/$row->id";
}
This assumes 'id' as a primary key and that 'slug' will be unique
Inside your controller, you can obtain the id by:
$id = $this->uri->rsegment(3);