I am new to PDO and I have pretty simple question. I have a simple function for connecting to DB:
function connectDB()
{
try {
$dbh = new PDO('mysql:host='.Config::$db_server.';dbname='.Config::$db_name, Config::$db_login, Config::$db_password, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->exec("SET CHARACTER SET utf8");
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
After calling this function I successfully connect to db. Later when trying to send a query using $dbh->query I got "Call to a member function query() on a non-object ". I do understand that - I don't have an instance of the class at the moment. But the only think to achieve that is to use $dbh = new PDO("settings") again, which is kind of stupid isn't? The function has no sense than. I tried to return the $dbh in the connectDB function (before the NULL statement) but it wasn't really working.
How should be this done properly?
It depends on your app's architecture, but I believe, you should make database handle a class variable, initialize it in constructor and use it later.
class DatabaseAccess{
private $_db;
public function __construct(){
try {
$this->_db = new PDO('mysql:host='.Config::$db_server.';dbname='.Config::$db_name, Config::$db_login, Config::$db_password, array(
PDO::ATTR_PERSISTENT => true
));
$this->_db->exec("SET CHARACTER SET utf8");
//notice I removed "= null" part
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
public function getSomething(){
//run your query here:
return $this->_db->query('');
}
}
You need to remove the $dbh = null; sentence in your function. With this sentence you are overwriting the connection with a null value, so anytime later you do $dbh->query(), it's like doing null->query(), and so that error appears.
Also, you need to save the handler, or it gets lost after your code exits that function. Add a return $dbh; at the end of your function or wrap it in a class.
Related
I'm working on project, I faced some problems
If I fill all fields and then submit there is no problem and it saved to database, but my issue if some field is empty the validation messages error appear in another page as JSON format.
I don't use any AJAX code in my view file.
Here is controller code:
public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');
And here is RegisterRequest code:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];
Can you help me please?
Your errors should be accessible inside blade file with $errors variable which you need to iterate and display the errors.
Link to doc which will help you with the render part - https://laravel.com/docs/7.x/validation#quick-displaying-the-validation-errors
Clearly from doc as well
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
https://laravel.com/docs/7.x/validation#creating-form-requests
Also refactor the code a bit as following to run only one query to create a user instead of creating and then updating.
public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(\Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}
I have a problem with my code, the first code is like
<?php
require_once('zend/json.php');
require_once('zend/db.php');
//require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>'localhost',
'username'=>'stet',
'password'=>'test',
'dbname'=>'test'
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from info ";
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
and it works well, but I want to make it like
<?php
include ('table.php');
include ('config.php');
require_once('zend/json.php');
require_once('zend/db.php');
require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>$dbhost,
'username'=>$dbuser,
'password'=>$dbpass,
'dbname'=>$dbdb
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from ".$table;
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
I don't know whats wrong with this code, I need help.
the error message Notice: Undefined variable: dbdb in C:\wamp....
The config.php is only have code like $dbpass = 'test'; and like that, I'm creating a simple web and I want to make my code to other database and aplikasi, so I only changed the config.php and the table.php
for the table.php maybe will work if the config.php work.
Thanks.
You are using a class and not paying attention to variable scope.
I understand you have variables with values for the DB connection in that config.php file. Although these variables are available inside the script file with the include they are NOT available and accessible inside your class. The only difference would be any constants with define (or variables inside a global which is not a good idea).
You could create a config class inside the config.php and set the values as properties then instantiate that class inside your _koneksi method. And then you would use a require_once instead of the include.
UPDATE
So here's an example that is similar to your file where your include ('config.php'); is essentially the same as declaring your variables directly before the class begins.
// variable defined outside the class
$foo = 'foo';
class demo
{
public $bar = 'bar';
function test()
{
$foobar = 'foobar';
echo 'Class property $bar is:' . $this->bar . PHP_EOL;
echo 'Local variable $foobar is:' . $foobar . PHP_EOL;
}
function run()
{
if (isset($foo)) {
echo 'Global variable $foo is:' . $foo . PHP_EOL;
} else {
// This is where you have your problem.
// Variables from outside the class are not available.
echo 'Global variable $foo not found' . PHP_EOL;
}
}
}
$demo = new demo();
$demo->test(); // Class property $bar is:bar
// Local variable $foobar is:foobar
$demo->run(); // Global variable $foo not found
echo 'Variable $foo is: ' . $foo . PHP_EOL; // Class property $bar is:bar
I would like to know how to avoid the instruction "return" inside a function in Symfony2. In other words how can I make a void function which doesn't return anything. In fact I have tried that for a long time but every time I run the code I did I see this error message: "The controller must return a response" ... By the way, this is the code that I have:
public function AddeventsgroupeAction(Request $request) {
$eventg = new eventsgroupe();
$form = $this->createForm(new eventsgroupeType(), $eventg);
$em = $this->getDoctrine()->getManager();
$securityContext = $this->get('security.context');
$token = $securityContext->getToken();
$user = $token->getUser();
$id = $user->getId();
$groupe=$this->getRequest('groupe');
$idg = intval($groupe->attributes->get('id'));
$qb = $em->createQueryBuilder();
$qb->select('l')
->from('IkprojGroupeBundle:Groupe', 'l')
->from('IkprojGroupeBundle:eventsgroupe', 'e')
->where(' l.id = :g and e.idGroupe = l.idAdmin and l.id = e.idEventGroupe');
$qb->setParameter("g", $idg);
$query = $qb->getQuery();
$res = $query->getResult();
$rows = array();
foreach ($res as $obj) {
$rows[] = array(
'id' => $obj->getId());
}
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isValid()) {
$eventg-> setIdGroupe($id);
$eventg-> setIdEventGroupe($idg);
$em->persist($eventg);
$em->flush();
return $moslem="yes";
}
} else {
return $this->render('IkprojGroupeBundle:GroupeEvents:Addeventgroupe.html.twig', array(
'groupe' => $rows,
'event' => $eventg,
'form' => $form->createView(),
));
}
}
How can I replace the instruction : return $moslem="yes"; in order to not return anything??...Is that possible??
To answer your basic question, a simple return will return a void from your function.
The "controller must return a response" message actually comes from the request handler. You need to tell the request handler what you want it to do. There is no default page so a void return will trigger the error.
In most cases, after successfully processing a posted form you will want to return a redirect response.
Something like:
$form->handleRequest($request);
if ($form->isValid()) {
...
$em->flush();
return $this->redirect($this->generateUrl('task_success'));
I should point out that your form code seems to be from S2.1 or older. It's unnecessarily complicated. You should be using at least 2.3. Make sure you are looking at the correct version of the documentation. Hint: the isValid() takes care of the POST check.
http://symfony.com/doc/current/book/forms.html#handling-form-submissions
It's also worth while to understand the request/response workflow.
http://symfony.com/doc/current/book/http_fundamentals.html
Digging into the code can also help in understanding where the error message is coming from:
Symfony\Component\HttpKernel\HttpKernel#handleRaw($request)
Simple, delete the else statement and if $request->isMethod('POST') or $form->isValid() returns false the code inside will not be executed then the script return the default view.
EDIT: you can also make a redirect with a flash message where needed like this:
$this->get('session')->getFlashBag()->add('success', 'your success message');
return $this->redirect($this->generateUrl('your_route'));
Remember to add support for flash message in your view looking at the Symfony2 docs
I'm extracting two different sets of data from a function in my model (syntax below). I'm trying to display the data my view. I put the variable in var_dump and var_dump is displaying the requested information but I'm having a hard time accessing that information. I'm getting two different sets of error messages as well. They are below. How would I display the information in my view? Thanks everyone.
Site Controller
public function getAllInformation($year,$make,$model)
{
if(is_null($year)) return false;
if(is_null($make)) return false;
if(is_null($model)) return false;
$this->load->model('model_data');
$data['allvehicledata'] = $this->model_data->getJoinInformation($year,$make,$model);
$this->load->view('view_show_all_averages',$data);
}
Model_data
function getJoinInformation($year,$make,$model)
{
$data['getPrice'] = $this->getPrice($year,$make,$model);
$data['getOtherPrice'] = $this->getOtherPrice($year,$make,$model);
return $data;
}
function getPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
function getOtherPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
View
<?php
var_dump($allvehicledata).'<br>';
//print_r($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo "Cities of " . $allvehicledata->cardescription_id . "<br />";
$id = $allvehicledata['getPrice']->id;
$model = $allvehicledata[0]->model;
$make = $allvehicledata->make;
echo "$id".'<br>';
echo "$make".'<br>';
echo "$model".'<br>';
echo $allvehicledata->year;
}
?>
Error Messages
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 7
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 9
In your controller you are assigning the result of function getJoinInformation to the variable allvehicledata. This variable is then assigned to the view.
The function getJoinInformation is returning an array with the following
$data = array(
'getPrice' => $this->getPrice($year,$make,$model),
'getOtherPrice' => $this->getOtherPrice($year,$make,$model)
);
So in your view you can access the attributes getPrice and getOtherPrice in the object $allvehicledata like
$allvehicledata->getPrice;
$allvehicledata->getOtherPrice;
In line 7 you try to access the attribute cardescription_id, which is not an attribute of the object $allvehicledata.
I think this is an attribute which is get from the db query, so you should try to access it allvehicledata->getPrice->cardescription_id or allvehicledata->getOtherPrice->cardescription_id.
In line 9 you try to access some data stored in an array $model = $allvehicledata[0]->model;, but $allvehicledata is not an array.
By reading on stackoverflow I solved almost all of my problems. But now I've got a very "special" one I can't explain. Hours of googling and researching, but there is no solution.
class:
class Beitrag_Loeschen {
private $debug;
private $do_debug;
function __construct() {
$this->do_debug = TRUE;
}
function __destruct() {
if ($this->do_debug == TRUE) {
mysql_query("INSERT INTO `seite_log` (`id`, `timestamp`, `benutzer_ip`, `benutzer_id`, `datei`, `referrer`, `fehler`, `kommentar`) VALUES (NULL, UNIX_TIMESTAMP(), '', 1, '', '', '', '')");
}
}
private function _deleteDir($dir) {
// more code
}
// SQL-Query
private function _queryDelete($tabelle, $spalte, $id) {
$query = "DELETE FROM `".sql($tabelle)."` WHERE `".sql($spalte)."`='".sql($id)."';";
mysql_query($query);
$this->debug .= $query."<br/>";
}
private function _queryDeleteKat($tabelle, $kat, $kat_id) {
$query = "DELETE FROM `".sql($tabelle)."` WHERE `kat`='".sql($kat)."' AND `kat_id`='".sql($kat_id)."'";
mysql_query($query);
$this->debug .= $query."<br/>";
}
private function _seiteSuchbegriffe($ergebnis_typ, $ergebnis_id) {
$query = "DELETE FROM `seite_suchbegriffe` WHERE `ergebnis_id`='".sql($ergebnis_id)."' AND `ergebnis_typ`='".sql($ergebnis_typ)."'";
mysql_query($query);
$this->debug .= $query."<br/>";
}
// Kommentare
function bewertungKommentar($id) {
$this->_queryDelete('bewertungen_kommentare', 'id', $id); // bewertungen_kommentare
}
function fotoKommentar($id) {
$this->_queryDelete('fotos_kommentare', 'id', $id); // fotos_kommentare
}
function rezeptKommentar($id) {
$this->_queryDelete('rezepte_kommentare', 'id', $id); // rezepte_kommentare
}
// Bewertung
function bewertung($id) {
$this->_queryDelete('bewertungen_burger', 'id', $id); // bewertungen_burger
$this->_queryDelete('bewertungen_kommentare', 'bewertung_id', $id); // bewertungen_kommentare
// more code
}
// Foto
function foto($id) {
$this->_queryDelete('fotos_kommentare', 'foto_id', $id); // fotos_kommentare
// more code
}
// Burger
function burger($id) {
$this->_queryDelete('burger', 'id', $id); // burger
$this->_queryDeleteKat('benutzer_aktionen', 'favorit_burger', $id); // benutzer_aktionen
// more code
}
// Lokalität
function lokalitaet($id) {
$this->_queryDeleteKat('seite_korrekturen', 'lokalitaet', $id); // seite_korrekturen
$this->_queryDeleteKat('seite_hits', 'lokalitaeten', $id); // seite_hits
// more code
}
}
My concept: If you want to, e. g., delete a location you have to delete rows from several tables. For this purpose I wrote this little PHP class. While deleting the stuff there are performed many mysql queries in many tables and therefore I needed a way to debug.
The debug information are stored in $debug.
$this->debug .= $query."<br/>";
Finally, $debug should stored in the database (after calling the class there is a "header("Location: ...")", so I could not perform an "echo"). The DB query for this is called in the destructor (INFO: the query is only a dummy. So I could obviate that there is no problem with the query-syntax):
function __destruct() {
if ($this->do_debug == TRUE) {
mysql_query("INSERT INTO `seite_log` (`id`, `timestamp`, `benutzer_ip`, `benutzer_id`, `datei`, `referrer`, `fehler`, `kommentar`) VALUES (NULL, UNIX_TIMESTAMP(), '', 1, '', '', '', '')");
}
}
The class is called by this:
$del = new Beitrag_Loeschen();
$del->bewertungKommentar($id);
//header("Location: ".$referer);
THE PROBLEM:
There seems to be no db connection within the destructor, because I got this error all the time:
Warning: mysql_query() [function.mysql-query]: Access denied for user ''#'localhost' (using password: NO) in /[...]/classes/beitrag_loeschen.inc.php on line 12
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /[...]/classes/beitrag_loeschen.inc.php on line 12
(line 12 is the mysql_query in the destructor)
What am I doing wrong? The other mysql_querys in the class are working perfectly.
Thank you!
Unless you are explicitly calling the __destruct() function or handling your references to the object very closely and know exactly when it gets unset there is no guarantee when __destruct() will be called by the language. By the time it is called the language has already released the resource for your connection to the database. mysql_query() attempts to create a new connection, using the default server parameters and fails to do so because there is no blank user.
To reliably log your information you need to explicitly make the call to run the query. If you rely on __destruct() for this you will likely always encounter some problem similar to the one you're having.