i'm working on admin panel form and i have a problem in connect form page to mysql .. i made table name : main_settigns and i'm working with MVC .. this is the form controller :-
enter code here
<?php
if(isset($_POST['submit']) && $_POST['submit'] == "Update")
{
$mainsettings['site_name'] = $_POST['site_name'];
$mainsettings['site_url'] = $_POST['site_url'];
$mainsettings['site_desc'] = $_POST['site_desc'];
$mainsettings['site_email'] = $_POST['site_email'];
$mainsettings['site_tags'] = $_POST['site_tags'];
$mainsettings['site_homapanel'] = $_POST['site_homapanel'];
$mainsettings['fb'] = $_POST['fb'];
$mainsettings['tw'] = $_POST['tw'];
$mainsettings['yt'] = $_POST['yt'];
$mainsettings['username'] = $_POST['username'];
try {
include 'models/Arageek.php';
include 'models/Add.php';
$addmMainSettings = new Add($mainsettings, "main_settigns");
if($addmMainSettings == TRUE)
{
echo 'successfully Added';
}
}
catch (Exception $exc)
{
echo $exc->getMessage();
}
}
else
{
try {
include 'models/Arageek.php';
include 'models/Display.php';
$data = new Display("main_settigns");
$displayData = $data->getData();
} catch (Exception $exc)
{
echo $exc->getMessage();
}
include 'views/v_mainSettings.php';
}
?>
this is the model page :-
enter code here
<?php
/* add class
* insert the data into mysql database
* #author Dev.Yasser
*/
class Add extends Arageek
{
private $data;
private $tablename;
private $cxn;
public function __construct($data, $tablename)
{
if(is_array($data))
{
$this->data = $data;
$this->tablename = $tablename;
}
else
{
throw new Exception("Error: the data must be in an array .");
}
$this->connectToDB();
$this->AddData($this->data);
$this->close();
}
// insert the data into the table
function AddData($data)
{
foreach ($data as $key=> $value)
{
$keys[] = $key;
$values[] = $value;
}
$tblKeys = implode($keys, ",");
$dataValues = '"'. implode($values, '","') .'"';
$query = "INSERT INTO $this->tablename ($tblKeys) VALUES ($dataValues)";
if($sql = mysql_query($query))
{
return TRUE;
}
else {
throw new Exception("Error: Can not excute the query");
return FALSE;
}
}
}
?>
and the parent class :-
enter code here
<?php
class Arageek {
private $cxn;
function connectToDB()
{
include 'models/Database.php';
$vars = "include/vars.php";
$this->cxn=new Database($vars);
}
function close()
{
$this->cxn->close();
}
}
?>
the result after submit the form is : "Error: Can not excute the query"
Related
I want to CREATE DATABASE and in same database want to import data. But what i tried since getting no luck.
Action
public function actionRestore($id = null)
{
$list = $this->getFileList();
$file = $list[$id];
if(isset($file))
{
$transaction = Yii::$app->db->beginTransaction();
try{
$sql = 'DROP DATABASE IF EXISTS '.$this->getDbName().';CREATE DATABASE '.$this->getDbName();
$sqlFile = $this->path . basename($file);
Yii::$app->db->pdo->prepare($sql,$this->execSqlFile($sqlFile));
if(Yii::$app->db->pdo->exec())
{
$transaction->commit();
Yii::$app->session->setFlash('success', 'Backup Restored Successfully');
return $this->redirect(['index']);
}
$transaction->rollback();
}
catch(\Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', "Backup not Restored. <br>".$e->getMessage());
return $this->redirect(['index']);
}
}
}
I am not sure about execSqlFile() method :
public function execSqlFile($sqlFile)
{
$flag = false;
if (file_exists($sqlFile))
{
$sqlArray = file_get_contents($sqlFile);
$cmd = Yii::$app->db->createCommand($sqlArray);
try {
$cmd->execute();
$flag = true;
}
catch(Exception $e)
{
$flag = false;
throw new \yii\db\Exception($e->getMessage());
}
}
return $flag;
}
1) getDbName() gets database name.
1) getFileList() gets file to be executed in execSqlFile().
I am not getting any error or message of success or failure.
I want to combine both into one preparedStatement, but don't know what i am missing here.
I found the solution i need to use shell_exec:
public function execSqlFile($sqlFile)
{
if (file_exists($sqlFile))
{
$database=array();
$db=Yii::$app->db;
$database=explode(";",$db->dsn);
$dbname=explode("=",$database['1']);
$output = shell_exec('mysql -u '.$db->username.' -p'.$db->password.' '. $dbname['1'] .'< '.$sqlFile);
}
return $output;
}
Don't use PDO object directly. You loose abstractions. I would just execute two commands like this:
public function actionRestore($id = null)
{
if($id !== null && $this->restoreDatabase($id)) {
Yii::$app->session->setFlash('success', 'Backup Restored Successfully');
} else {
Yii::$app->session->setFlash('error', "Backup not Restored. <br>" . $e->getMessage());
}
return $this->redirect(['index']);
}
private function restoreDatabase($id)
{
$list = $this->getFileList();
$file = $list[$id];
if (isset($file)) {
$transaction = Yii::$app->db->beginTransaction();
try {
Yii::$app->db->createCommand('DROP DATABASE IF EXISTS ' . $this->getDbName() . '; CREATE DATABASE ' . $this->getDbName())->execute();
$sqlFile = $this->path . basename($file);
$this->execSqlFile($sqlFile);
$transaction->commit();
return true;
} catch (\Exception $e) {
$transaction->rollBack();
Yii::error($e->getMessage()); //Probably throw exception?
return false;
}
}
}
private function execSqlFile($sqlFile)
{
if (!file_exists($sqlFile)) {
return false;
}
$sql = file_get_contents($sqlFile);
$command = Yii::$app->db->createCommand($sql);
try {
$command->execute();
return true;
} catch (Exception $e) {
throw new \yii\db\Exception($e->getMessage());
}
}
I have been trying to insert a new line to mysql db but insert(){...} function has inserted duplicate lines.
I also have tried several methods to insert but it doesn't works. All of the methods have inserted duplicate rows .
How can I fix the problem? Do you have any idea?
Thank you for your help & advice.
protected $db;
public function __construct() {
try {
$this->db = new mysqli('localhost', 'root', '', 'trigger');
$this->db->set_charset("utf8");
} catch (mysqli_sql_exception $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
}
public function select($table, $rows = "", $where = "", $return_type = "") {
if (empty($rows)) {
$rows = "*";
}
if (empty($where)) {
$where = "";
} else {
$where = "where " . $where;
}
try {
$query = $this->db->query("SELECT $rows FROM $table $where");
if ($return_type == "json") {
return json_encode($query);
} else {
return $query;
}
} catch (mysqli_sql_exception $exc) {
return $exc->getMessage();
}
}
public function insert($table, $params) {
$_keyArr = array();
$_valueArr = array();
foreach ($params as $key => $value) {
$_keyArr[] .= $key;
$_valueArr[] .= $value;
}
$keys = implode("`,`", $_keyArr);
$values = implode("','", $_valueArr);
$query = $this->db->query("INSERT INTO `$table` (`$keys`) VALUES('$values')");
try {
return $query;
} catch (mysqli_sql_exception $ex) {
return $ex->getMessage();
}
}
-------------Answer to matt-------------
I call with following code:
if ($this->db->insert("table_name", array("path" => "test", "flow_name" => "test"))) {
echo 'ok';
} else {
echo 'not ok';
}
-------------Answer to Pavel-------------
"REPLACE INTO" didn't work. The problem occured again.
Just use REPLACE INTO instead INSERT INTO
$query = $this->db->query("REPLACE INTO `$table` (`$keys`) VALUES('$values')");
I've tried everything I know but it's still not working. I cannot get any posted data from my HTML form and I know it's not getting the data from the HTML form because I've tried to change the values and execute without the form and then it works.
Here is my html form:
<?php
ob_start();
session_start();
error_reporting(E_ALL);
if (!ini_get('display_errors')) { ini_set('display_errors', '1');}
include 'classes/user.class.php';
include 'classes/database.class.php';
include 'classes/config.class.php';
include 'classes/bcrypt.class.php';
if(isset($_POST['submitted'])) {
$user = new MonetizeMedia\Classes\User;
$db = new MonetizeMedia\Classes\Database;
$username = $_POST['username'];
$password = $_POST['password'];
$user->username = $username;
$user->password = $password;
if($user->createUser()) {
echo "DONE!";
}
else
{
echo "<br />An error occured while creating your account. Please try later.";
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Register</title>
</head>
<body>
<form method="post" action="">
<ul>
<li>
<label for="usn">Username : </label>
<input type="text" name="username" />
</li>
<li>
<label for="passwd">Password : </label>
<input type="password" name="password" />
</li>
<li class="buttons">
<input type="submit" name="submitted" value="Register" />
</li>
</ul>
</form>
</body>
</html>
my user class
<?php
namespace MonetizeMedia\Classes;
class User {
private $uid;
private $fields;
public function __construct() {
$this->uid = null;
$this->fields = array('username' => '',
'password' => '');
}
public function __get($field) {
if($field == 'uid')
{
return $this->uid;
}
else
{
return $this->fields[$field];
}
}
public function __set($field, $value) {
if(array_key_exists($field, $this->fields))
{
$this->fields[$field] = $value;
}
}
public function validateUsername($username) {
return preg_match('/^[a-zA-Z]{4,15}$/i', $username);
}
public function validateEmailAddr($email) {
return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);
}
public function getUserById($id) {
$user = new \MonetizeMedia\Classes\User;
$db = new \MonetizeMedia\Classes\Database;
$sql = "SELECT * FROM users WHERE uid = :uid";
$db->prepare($sql);
$db->bindParam(":uid", $id);
$row = $db->fetchAll();
$user->uid = $row['uid'];
$user->username = $row['username'];
$user->password = $row['password'];
return $user;
}
public function getByUsername($username) {
$user = new \MonetizeMedia\Classes\User;
$db = new \MonetizeMedia\Classes\Database;
$sql = "SELECT * FROM users WHERE username = :username";
$db->prepare($sql);
$db->bindParam(":username", $username);
$row = $db->fetchAll();
$user->uid = $row['uid'];
$user->username = $row['username'];
$user->password = $row['password'];
return $username;
}
public function createUser() {
try {
$username = null;
$password = null;
$db = new \MonetizeMedia\Classes\Database();
$bcrypt = new \MonetizeMedia\Classes\Bcrypt(15);
/*** query ***/
$sql = 'INSERT INTO users(username, password) VALUES(:username, :password)';
/*** prepare the select statement ***/
$db->prepare($sql);
/*** bind the parameters ***/
$db->bindParam(":username", $username);
$db->bindParam(":password", $bcrypt->hash($password));
//$db->bindParam(":username", "test");
//$db->bindParam(":password", $bcrypt->hash("test"));
/*** execute the prepared statement ***/
$db->execute();
$result = $db->fetchAll();
return $result;
} catch ( \PDOException $e ) {
return $e->getMessage();
}
}
}
?>
Here is my database class:
<?php
namespace MonetizeMedia\Classes;
use PDO;
class Database {
private $db = array();
private $dbh;
private $error;
private $stmt;
public function __construct() {
$Config = new \MonetizeMedia\Classes\Config;
$this->db['username'] = $Config->DB_USERNAME;
$this->db['password'] = $Config->DB_PASSWORD;
$this->db['database'] = $Config->DB_DATABASE;
$this->db['server'] = $Config->DB_SERVER;
$this->db['port'] = $Config->DB_PORT;
$this->db['encoding'] = $Config->DB_ENCODING;
try {
/* Create a connections with the supplied values */
$this->dbh = new \PDO("mysql:host={$this->db['server']};dbname={$this->db['database']};port={$this->db['port']};charset={$this->db['encoding']}", $this->db['username'], $this->db['password']);
$this->dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); // throw exceptions on errors (default: stay silent)
$this->dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); // important! use actual prepared statements (default: emulate prepared statements)
$this->dbh->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_CLASS); // fetch associative arrays (default: mixed arrays)
$this->dbh->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8" ); // set encoding to utf8
} catch( \PDOException $e ) {
/* If any errors echo the out and kill the script */
echo "<center><b>[DATABASE] Error - Connection Failed:</b> " . $this->error = $e->getMessage() . "<br/><br/><br/></center>";
echo "<center><b>We are currently experiencing technical difficulties. We have a bunch of monkeys working really hard to fix the problem.</b></center>";
die();
}
}
public function prepare($sql) {
try {
$this->stmt = $this->dbh->prepare($sql);
} catch ( \PDOException $e ) {
$e->getMessage();
// throw new InvalidSQLException("Invalid SQL. Statement could not be prepared.");
}
}
public function bindParam($param, $value, $type = null) {
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
break;
}
}
return $this->stmt->bindParam($param, $value, $type);
}
public function execute() {
try {
return $this->stmt->execute();
} catch ( \PDOException $e ) {
$e->getMessage();
}
}
public function fetchAll() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch() {
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount() {
return $this->stmt->rowCount();
}
public function lastInsertId() {
return $this->dbh->lastInsertId();
}
public function beginTransaction() {
return $this->dbh->beginTransaction();
}
public function endTransaction() {
return $this->dbh->commit();
}
public function cancelTransaction() {
return $this->stmt->rollBack();
}
public function debugDumpParams() {
return $this->stmt->debugDumpParams();
}
public function errorInfo() {
return $this->dbh->errorInfo();
}
public function countAll($arr) {
return count($arr);
}
}
?>
I've been sitting with this problem for more than 10 hours without a proper solution.
What exactly is not working?
Anyways, you should rewrite your createUser method:
$username = null;
$password = null;
I'm creating a web app with various classes for things like the user, Smarty template control, etc.
I already have a database class which is all well and good, but I'm concerned about the performance of it.
Currently, in another class, I'm doing $this->db = new DB() to create a local database instance, however the database class's __construct() function creates a new connection to the MySQL server every time I make a new DB() instance, which is obviously less than sensible. This means that each instance of all my different classes that uses the database class makes a connection to the server. I don't have a vast amount of classes, but I only want one per page load.
This is a stripped down sample of what I have at the moment:
// Database class used by multiple other classes
class DB {
private $dbh;
function __construct() {
$this->dbh = // PDO connection here
}
public function query($str) {
// Do a query
}
}
// Example class User
class User {
private $db; // Stores local instance of DB class.
function __construct() {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
I'm looking for the "best" or most common practice of doing this. I don't want to make 10-ish separate connections for each page load.
I want to know what the best way of using and managing a DB class in my application. My four thoughts are these:
Would using a persistent connection to the MySQL server solve this multiple connection issue for me?
Should I use a static factory class and return a DB instance instead of using new DB()?
Is the proper solution to use an entirely static class and just do DB::query() (for example) every time I reference it?
I often use multiple classes in another (so we might have class Folders which requires classes User, DB and Smarty). Is it general practice to extend each class somehow?
If you make the variable holding the connection static, then you can check if you already established a connection. Static variables are the same across all instances of the class, so you can create 100 instances that all use the same connection. You just need to reference it statically: self::$dbh instead of $this->dbh.
class DB {
private static $dbh = null;
function __construct() {
if ( is_null(self::$dbh) ) {
self::$dbh = // PDO connection here
}
}
}
I would suggest you to check the $this -> db at first and then only create it.
function __construct() {
if(!isset($this -> db) || !is_a("DB", $this -> db)) {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
}
You need to inject db connection to your class instead of creating a new connection.
// In a bootstrap file
$db = new DB();
// User.php
class User {
private $db;
function __construct($db=null) {
if (!is_null($db)) {
$this->setConnection($db);
}
}
function setConnection($db) {
$this->db = $db;
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
BTW, Zend_Registry is a good solution if you prefer it http://framework.zend.com/manual/en/zend.registry.using.html
<?php
class DBLayer {
public $prefix;
public $link_id;
public $query_result;
public $saved_queries = array();
public $num_queries = 0;
public function DBLayer() {
$db_prefix = '';
$this->prefix = $db_prefix;
if (isset($this->link_id)) {
return $this->link_id;
}
$this->link_id = #mysql_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, true);
if ($this->link_id) {
if (#mysql_select_db(DATABASE_NAME, $this->link_id)) {
return $this->link_id;
} else {
$this->wplog("Unable to select database. Host:". DATABASE_HOST. "Database:" . DATABASE_NAME . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
} else {
$this->wplog("Unable to connect to MySQL server. Host: " . DATABASE_HOST . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
}
public function query($sql, $unbuffered = false) {
if(LOG){echo "<hr>$sql";}
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result) {
return $this->query_result;
} else {
$msg= $sql . "<br /> Error: (" . mysql_errno() . ") " . mysql_error();
$this->wplog($msg);
}
}
public function result($query_id = 0, $row = 0) {
return ($query_id) ? #mysql_result($query_id, $row) : false;
}
public function fetch_assoc($query_id = 0) {
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
public function fetch_row($query_id = 0) {
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
public function num_rows($query_id = 0) {
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
public function affected_rows() {
return ($this->link_id) ? #mysql_affected_rows($this->link_id) : false;
}
public function insert_id() {
return ($this->link_id) ? #mysql_insert_id($this->link_id) : false;
}
public function get_num_queries() {
return $this->num_queries;
}
public function get_saved_queries() {
return $this->saved_queries;
}
public function free_result($query_id = false) {
return ($query_id) ? #mysql_free_result($query_id) : false;
}
public function escape($str) {
if (function_exists('mysql_real_escape_string'))
return mysql_real_escape_string($str, $this->link_id);
else
return mysql_escape_string($str);
}
public function get_select($q, $onlyone=false) {
$results = array();
$r = $this->query($q);
if ($onlyone) {
return $this->fetch_assoc($r);
}
while ($l = $this->fetch_assoc($r)) {
$results[] = $l;
}
return $results;
}
public function get_error() {
return mysql_error();
}
public function close() {
if ($this->link_id) {
if ($this->query_result)
#mysql_free_result($this->query_result);
return #mysql_close($this->link_id);
}
else
return false;
}
public function auto_execute($table, $data, $type, $criteria='') {
$result = $this->get_select("desc " . $table);
if ($type == "INSERT")
$start = "insert into " . $table . " set ";
elseif ($type == "UPDATE")
$start = "update " . $table . " set ";
$sql = $start;
foreach ($result as $rst) {
foreach ($data as $key => $value) {
if ($key == $rst['Field'] and $key !== 0) {
if ((#ereg('date', $rst['Type'])) && $value == '') {
$sql = $sql . "`".$key."`" . "=NULL, ";
} elseif ((!#ereg('int', $rst['Type']))) {
$sql = $sql . "`".$key."`" . "='" . $value . "', ";
} else {
if (trim($value) != "") {
$sql = $sql . "`".$key."`" . "=" . $value . ", ";
}
}
}
}
}
if ($sql == $start)
return 0;
else {
$sql = substr($sql, 0, strlen($sql) - 2);
if ($type == "UPDATE" and !empty($criteria))
$sql = $sql . " where " . $criteria;
}
//echo $sql;exit;
if ($this->query($sql)) {
$return = $this->insert_id();
} else {
$return = 0;
}
return $return;
}
private function wplog($message) {
if(LOG==true){
$lineBreak = "\n"; // this function will NOT work on a windows server without further modification
$contents = date('Y-m-d H:i:s') . ' ' . $message. $lineBreak;
$myFile = SERVER_PATH.'/log.txt';
$fh = fopen($myFile, 'a') ;
fwrite($fh, $contents);
fclose($fh);
//SetFileContents(SERVER_PATH.'/log.txt',$contents,'a');
}
}
}
I have a php script, test.php that has the contents
<?php
require_once("classes/user.php");
echo "test";
?>
and here is the contents of user.php
<?php
class User {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
public __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
private id($id) { //select from database
require_once('config.php');
$pdo = new PDOConfig();
$sql = "SELECT * FROM users WHERE `id` = :id";
$q = $pdo->prepare($sql);
$q->execute(array(":id"=>$id));
$resp = $q->fetchAll();
foreach ($resp as $row) {
foreach ($row as $key=>$value) {
if(!is_int($key))
$this->data[$key] = html_entity_decode($value, ENT_QUOTES);
}
}
$pdo = null;
unset($pdo);
}
private create($arr) { //create new item from values in array and insert to db
}
public delete() {
$this->life = 0;
//update database "life" here
}
/* ##################################### */
/* !Functions */
/* ##################################### */
public projects($extra = null) {
$projects = array();
require_once('project.php');
$pdo = new PDOConfig();
$sql = "SELECT * FROM ---- WHERE `000` = :aaa";
if($extra) $sql .= " " . $extra;
$q = $pdo->prepare($sql);
$q->execute(array(":aaa"=>$this->id));
$resp = $q->fetchAll();
foreach ($resp as $row) {
$project = new Project($row['id']);
$projects[] = $project;
$project = null;
unset($project);
}
return $projects;
}
}
?>
and test is never printed, and on chrome the page doesn't load at all
The website encountered an error while retrieving http://example.com/test.php. It may be down for maintenance or configured incorrectly.
I can't figure this out for the life of me. Thanks it advance
You have a syntax error in the declaration of your __construct() method :
public __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
You need to use the function keyword, like this :
public function __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
To help find those errors, on your development computer, you should enable :
error_reporting
and display_errors
In fact, I just copy-pasted your code to a .php file and ran it -- and got a nice
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
in /home/.../temp/temp.php on line 39