Call controller from controller in PHP MVC? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Can i call admin panel controller from account controller?
I mean in account controller i set acessible parts of admin panel and i want to transfer that variable with accessible place to admin panel controller.
and now can i do sth like:
<?php
// Code here
$this->panel = new Admin_Panel();
$this->panel->accessibleparts = $this->data['accessible'];
?>
Or is it disallowed in mvc rules?

Stuff like this:
public function connect(){
try {
$db = new PDO('mysql:host=localhost;dbname=radiolev_db', 'radiolev_user', 'ceowwyso1');
is all fine and dandy, but you're not actually storing that database connection object anywhere in your object. It's just a local variable in that particular method, and will be destroyed when the function exits. e.g. you're connecting, then as soon as your connct() method returns, the local $db variable goes out of scope, and your brand new database connection is closed and destroyed.
You need to store that $db in your OWN object, so it'll be preserved for later use, e.g:
$this->db = new PDO(...);
instead.
And as everyone else above has said, you cannot mix mysql_(), mysqli_(), and PDO connections with each other. Each is a completely distinct and separate library (even though they all use the same underlying mysql low-level library). A connection established in one of those is completely distinct/separate/unusuable by the other libraries. Since you're using PDO to connect, you cannot use mysql_ functions, because mysql_ has no knowledge of anything going on in PDO.

The answer is read about how it works in the manual: http://php.net/oop5
Answer to your previous question:
You get the following errors:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'radiolev'#'localhost' (using password: NO) in /home/radiolev/public_html/top/toplist.class.php on line 10
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/radiolev/public_html/top/toplist.class.php on line 10
You then ask:
I don't understand why it appears cause the mysql passwords are good.
No worries. You just made a little mistake. The mistake is that you make use of the function mysql_real_escape_string while not using a connection of the mysql_* extensions (note: extension, not database server).
In case you're calling that function without establishing a mysql_* extension database connection, PHP will automatically create one based on the settings provided in php.ini. That is normally only the host set to localhost - but wihout username and password.
This is why you see the first error that the connection fails and the second error is the result of the failed connection - there is no link to the databse, so ?mysql_real_escape_string can not work.
To solve the problem, just do not use mysql_real_escape_string when you're using mysql via PDO. Prepared statements is all you need.

Your problem is that mysql_real_escape_string() expects a connection (which you have made, just not using the mysql_* subset of commands).
Use PDO, and actual prepared statements, not whatever it is you're doing now.
$pdo = $conn->prepare('SELECT * FROM myTable WHERE theColumn = :myParam');
$pdo->bindParam(':myParam', $_GET['data']);
$pdo->execute();
By 'call' I assume you mean use it.
Just add a return value, return $db; -- This would be at the end of your connect(), after the error mode was set.
Now
$db = new mysql();
$conn = $db->connect();
$conn->prepare('SELECT * FROM myTable WHERE myColumn = ?');
$conn->execute(array('test'));

Replace mysql_real_escape_string with PDO's quote or bindValue
You are getting a bunch of errors because mysql_real_escape_string is trying to use the last open connection used by mysql_connect (as explained in the PHP Manual). Since you are using PDO instead of the mysql_* functions, there is no connection and mysql_real_escape_string is throwing an error.

Related

Call to a member function prepare() on a non-object Error PHP mysql [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
Hello I have been finding issues in code that was working fine before
the $conn is giving error
It is a simple insert with pdo in Php
I have a connection class which works fine through i perform following operations in my file
// query
try{
$sql="INSERT INTO vup_file(filename,path,category,sub_category,user_id,comment,language,duration)
VALUES (:filename,:path,:category,:subcategory,:user_id,:comment,:language,:duration)";
global $conn;
$query=$conn->prepare($sql);
$query->execute
(array(':filename'=>$filename,':path'=>$path,':category'=>$category,':subcategory'=>$subcategory,':user_id'=>$user_id,':comment'=>$comment,':language'=>$language,':duration'=>$duration));
echo 'Success';
}catch(PDOException $e)
{
echo 'ERROR OCCURED : '.$e->getMessage();
}
}
I am getting a error of Call to a member function prepare() on a non-object in line 62
I tried to make $conn but that just didn't work
how to get rid of this error ?
As you have mentioned, you use mysql_query() in other file and it works fine.
It means you used mysql_connect().
It means you use procedure-style to connect to DB and create connection, but HERE you are trying to connect using OOP style and using connection created by mysql_connect().
It is impossible.
You need either to use OOP style to connect to DB:
$conn = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array( PDO::ATTR_PERSISTENT => false));
Or use procedure style to query DB instead of OOP-style:
mysql_query("INSERT INTO vup_file(filename,path,ca...
Procedure style is in past, now people mostly use OOP style, PDO objects.
PDO is the future, PDO is good.
And mysql_*() functions are in past, it is bad manner to write new code such way... Well it is explained here very well Why shouldn't I use mysql_* functions in PHP?
You global property $conn has not bee established correctly.
I would look back at your connection function and ensure that you have made a sucessful db connection.

How do I check the DB connection

I have host, database name, username and the password given as form inputs like:
$form['dbname']->getData()
I need to check if these data is correct for the mysql connection. So I chose to use mysql_connect() to check this:
$conn = mysql_connect($form['host']->getData(), $form['username']->getData(), $form['password']->getData(), $form['dbname']->getData());
if($conn) // ...
else // ...
But it displays some mysql_connect() warning with no other specific message...
What's wrong? Does the symfony 2 has any mechanism to check the connection?
Symfony uses repositories and entities to manage the database. The programmer doesn't manipulate the connection itself (Doctrine).
You could try to check a connection using PDO. Try to instance a PDO Object, and catch exceptions (PDOException for connection errors). However, you're "breaking" the framework's philosophy, trying to initiate an "extern" DB connection. If you need to work with several connections in Symfony, I suggest this reference :
http://symfony.com/doc/current/cookbook/doctrine/multiple_entity_managers.html
use the following format to receive the connection error if there is any.
$con = mysql_query() or die(mysql_error());

Warning: mysql_query(): 7 is not a valid MySQL-Link resource

Similar questions to this my have been asked a lot of times before. But since I did not find a solution in any of the questions asked before me, I take the liberty of asking it again.
My program uses a class made by me which handles all database connections for the program. Several modules I've used before used the same class without fail but when I chose to do a new module using the same class, the warning shows as-
Warning: mysql_query(): 7 is not a valid MySQL-Link resource in wherever... on line 49.
The warning happens when I execute a MySQL query through a function I made. The function is as follows-
public function runquery($_query)
{
$result = mysql_query($_query,$this -> connection); //line 49
if (! $result) die(mysql_error());
else return $result;
}
The function belongs to a class named mysql and it has not been tampered with or made changes to. So the function should technically work as expected, as every other module relying on the same class for database connectivity works just fine.
The query execution is successful however and I manage to update tables with no problems (except the warning). The block of code in the main program where the runquery() function is called from is as follows-
$phpmyadmin = new mysql();
$phpmyadmin->connect('localhost', 'root', '');
$phpmyadmin->setdb('test_db');
$result = $phpmyadmin->runquery($Query);
unset($phpmyadmin);
So the mysql's functions work just as fine as ever and the query executes just fine. But the warning shows for a reason I cannot understand. Any help?
The symptoms suggest that the database connection has been closed or dropped. Look for unwanted mysql_close() calls in your code. Additionally, you can use the following functions to troubleshoot the issue:
is_resource() and get_resource_type() to confirm that $this->connection is a valid data type.
mysql_ping() to find out if the database connection is alive.
If it's a rare issue, log stuff into a file and wait until it happens again.
There should not be spaces.
$result = mysql_query($_query,$this->connection);

Access denied error when using mysql_real_escape_string()

i am trying escape some data before it goes into my database, but i keep getting this error:
Warning: mysql_real_escape_string(): Access denied for user
Now this would usually suggest that i have not connected to the database (it also states (using password: NO)).
I was a little confused by this because when connecting to a database i have a 'die' clause so if it fails to connect i get told about it. So i tested this theory by running a simple query in the same function that im trying to escape the data and it works just fine.
So why on earth won't the escape method work or get a connection to the database. I did notice that the user the error states is not the user i use to access the database its something like 'www-data#localhost'. Could it be trying to log in with a different user, if so why and how? Because i another area of my website the escape function works just fine and i didn't do anything special to make it work, just added the code into my web page.
thanks for the help.
Are there any other ways of sanitizing my code?
Okay, so here we go, when the user submits the form, i use AJAX to collect the data and put it into an obj to post(JSON encoding) it to the first PHP script which is here:
http://codepad.org/kGPljN4I
This script checks all the data is there and then calls a function to add it to the database
this Mysql class is called to escape the data and then add a new record to the database, when and instance of the class is made it makes a connection to the database:
http://codepad.org/wwGNrTJm
The third file is for constants, it holds the information for the database like pass, user and so on:
http://codepad.org/dl0QQbi9
any better?
thanks again for the help.
The problem is that you have established your connection using MySQLi, but are then calling mysql_real_escape_string(). You intend to be calling mysqli_real_escape_string() either in procedural context, or object oriented contex.
class Mysql
{
private $conn;
function __construct()
{
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('No Connection to database!');
}
function add_non_member($data)
{
$email = $data->email;
// Procedural call
$san_email = mysqli_real_escape_string($this->conn, $email);
// Or OO call (recommended)
$san_email = $this->conn->real_escape_string($email);
// etc...
}
// etc...;
}
You're mixing ext/mysqli
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME
with ext/mysql functions:
$san_email = mysql_real_escape_string($email);
that last line should be
$san_email = $this->conn->real_escape_string($email);
I also got this access denied warning and I was able to find the solution. The problem is that I have not setup mysql db connection before calling mysql_real_escape_string function.
Solution:
Call mysql_connect($host, $user, $password) first (Or you can call your database connect function)
Then use mysql_real_escape_string($var)

Pass adodb connection to new php object

I'm trying to pass through an adodb connection to a class constructor but in doing so get this error:
mysql_error(): supplied argument is not a valid MySQL-Link resource
So to put it into context, I have instantiated a new adodb connection like this:
// establish database connection
$db = ADONewConnection($dsn);
if (!$db) die(mysql_error());
Then created my new user access object and passed in the adodb connection like this:
$user = new UserAccess($db);
This is the constructor from the user access class:
function UserAccess($oDbLink) {
// check we have a valid connection
}
Any ideas what I'm doing wrong?
Thanks,
Gaz
I can't see any obvious error in the part of code you supplied, so I'd suggest you:
leave aside the object for the time being
set your error_reporting() to E_ALL
double-check the parameters in $dsn - you may want to try to connect from the command line...
check your access privileges and run FLUSH PRIVILEGES
turn on ADODb debugging with $db->debug = TRUE;
test the thing from outside the object with a $db->Execute("SELECT * FROM tablename") or die($db->ErrorMsg());
When you get a message your connection resource is not a valid link - well, that's usually true. Don't forget to check the database is actually there and running.
The problem is most likely that you're attempting to use PHP's mysql_* functions with the $db object you get from ADONewConnection. It's not a mysql handle, so it won't work with those functions - you need to use adodb's own stuff.
Nothing wrong with your code, from what you've supplied. If you supply something more full then may be able to help.
Is there a real reason for passing a ADODB connection around? It'll just need to be passed everywhere and more work and without a real reason... I'd hesitate to do that. Even a standard global may be better (yes globals are evil) or perhaps a Singleton class?
Your code should be like this:
// establish database connection
$db = ADONewConnection($dsn);
if ( ! $db )
{
// just display error message
// you cannot use mysql_error, since you haven't connected to any database
die ("Cannot connect, check the parameter and make sure db is running!");
}
User reference, to avoid copying object
function UserAccess(&$oDbLink) {
// check we have a valid connection
}
Hope it help.
Thanks for your answers, I've managed to get this working by removing the $dsn variable and just passing in $_GLOBAL variables

Categories