Guys this is a code i have written. I have two files.
File one.
$regname=$_POST['name']; -----> here the variable passed is john suppose..
$sponserid=$_POST['sname'];
$regemail=$_POST['email'];
$regmobile=$_POST['mobile'];
include 'dbcon.php';
$obj = new dbcon;
$obj->createUser($regname,$sponserid,$regemail,$regmobile);
echo $obj;
in the above code i am getting variables from a form a and storing them. Then I instantiate an object and pass all those to a method.
My class code id like this.
class dbcon
{
public function __construct() //This is the connection construct.
{
$server = "localhost";
$user = "eplu";
$pass = "123456"; //Change on hosting server
$db = "epl";
mysql_connect($server, $user, $pass) or die("Error connecting to sql server: ".mysql_error());
mysql_select_db($db);
}
public function createUser($regname,$sponserid,$regemail,$regmobile){
$sql = "INSERT INTO onlinereg (names,sid,emails,mobiles) VALUES (`$regname`,`$sponserid`,`$regemail`,`$regmobile`)";
mysql_query($sql) or die(mysql_error());
return "Registration Success";
}
}
I get an error like Unknown column 'john' in 'field list'. New to OOPS pls help...Thnx in advance.....
Try now. This is not an OOPS related error, just the database thing.
class dbcon
{
public function __construct() //This is the connection construct.
{
$server = "localhost";
$user = "eplu";
$pass = "123456"; //Change on hosting server
$db = "epl";
mysql_connect($server, $user, $pass) or die("Error connecting to sql server: ".mysql_error());
mysql_select_db($db);
}
public function createUser($regname,$sponserid,$regemail,$regmobile){
$sql = "INSERT INTO onlinereg (names,sid,emails,mobiles) VALUES ('$regname','$sponserid','$regemail','$regmobile')";
mysql_query($sql) or die(mysql_error());
return "Registration Success";
}
}
Its because you are using backticks in your SQL query values. You need to use apostrophes instead of backticks, else the query will think you are referencing another column, in this case, 'john'
Change:
INSERT INTO onlinereg (names,sid,emails,mobiles) VALUES (`$regname`,`$sponserid`,`$regemail`,`$regmobile`)
to:
INSERT INTO onlinereg (names,sid,emails,mobiles) VALUES ('$regname','$sponserid','$regemail','$regmobile')
Simple change
`name`
to 'name'
You are using wrong quotes. This question is not really related to OOP
Related
I've been searching stack to get my answer, but nothing fixed my problem. So here's my shot:
$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
function GetArticle() {
global $conn;
$sql = "sql query";
$getresult = mysqli_query($conn, $sql);
..
}
This doesn't seem to work. If I put $conn inside the function, it works fine.
Any ideas?
I don't know your exact situation, but in general I do not see the benefit to using $conn as global. Your function depends on a mysqli connection in order to work, so just make the connection a function parameter.
function GetArticle($conn) {
$sql = "sql query";
$getresult = mysqli_query($conn, $sql);
..
}
Then after you have established your connection, you can call the function with your connection object as its argument.
$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
$article = GetArticle($conn);
I think this is a more manageable approach than trying to keep track of whether $conn is available in global scope before calling the function.
I'm in the process of upgrading from mysql to mysqli.
All my mysql code was procedural, and I'd now like to convert to OOP, as most mysqli examples online are in OOP.
The problem I'm having is that, with mysql, once I had set up a connection, I never had to inject that connection into any functions as arguments for mysql to be accessible in the function.
Here is my old connection code:
$location = "localhost";
$user = "rogerRamjet";
$pass = "bestPassInTheWorld";
$dbName = "myDBName";
$link = mysql_connect($location, $user, $pass);
if (!$link) {
die("Could not connect to the database.");
}
mysql_select_db("$dbName") or die ("no database");
And an example function that has access to the mysql connection, without $link needing to be injected into the function:
function getUser($data)
{
$data=mysql_real_escape_string($data);
$error = array('status'=>false,'userID'=>-1);
$query = "SELECT `user_id`, `user_email` FROM `myTable` WHERE `data`='$data'";
if ($result = mysql_query($query))
{
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ($row['user_id']!="")
{
return array( 'status'=>true, 'userID'=>$row['user_id'], 'email'=>$row['user_email'] );
}
else return $error;
}
else return $error;
}
And here's my new mysqli connection:
$mysqli=new MySQLi($location, $user, $pass, $dbName);
So, to upgrade the first line in the above function, I'd need:
$data = $mysqli->real_escape_string($data);
But that throws the error:
Undefined variable: mysqli
Does this mean that for any function needing access to $mysqli, I need to inject $mysqli as an argument into it, or is there a way for it to be accessible the way mysql is without injection?
I know I need to move to prepared statements, but this is just so I can get my head around mysqli basics.
Making the variable global is bad practice. The singleton pattern solves the issue of needing to share one instance of an object throughout an application lifecycle. Consider using a Singleton.
The crude solution would be global $mysqli; as first line of your function. But as hsan wrote, read about PHP variable scope
I'm rewriting my php code for mysql database access (now using a class definitions). While I had the old code (using old style functions) working I struggle to get the code for creating tables right - I think the problem relates in particular to the right definition of the sql statement, pls see code below. The new aspect (for me) compared to the old code is that the sql table creation command now must include the name of a database different than the master_database for which the PDO connection is set up (within the class constructor).
I looked at http://dev.mysql.com/doc/refman/5.6/en/create-table.html (I use mysql v5.6) - the part starting with "The table name can be specified as db_name.tbl_name to ..." but I cant get the sql syntax right. If I'm right the sql syntax is wrong what should be the right syntax in the code below for $sql (using the construction with various variables)?
Thnx for your help in advance.
Simplified code:
<?php
define('DB_HOST', '***');
define('DB_NAME', 'MASTER_DATABASE'); //different name
define('DB_USER', 'root');
define('DB_PASS', '*****');
//class definitions
class Database {
private $_db = null; //databasehandler
public function __construct() {
try {
$this->_db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS, array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
));
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_db->query('SET CHARACTER SET utf8');
} catch (PDOException $e) {
exit('Error while connecting to database.'.$e->getMessage());
}
}
private function printErrorMessage($message) {
echo $message;
}
public function createDBTable($dbname,$dbtable,$tablestructure) {
try {
$sql = "CREATE TABLE `".$dbname."'.'".$dbtable.$tablestructure; //NOT CORRECT YET
$success = $this->_db->exec($sql);
return ($success > 0) ? true:false;
}
catch(PDOException $e){
$this->printErrorMessage($e->getMessage());
}
}
}//class
//code using class defs
$dbname = 'Mydatabase'; //just an existing database
$dbtable = 'Persons';
$tablestructure = '(FirstName CHAR(30),LastName CHAR(30),Age INT)';
$mydb = new Database();
if($mydb->createDBTable($dbname,$dbtable,$tablestructure)){
echo 'table creation success';
}
else{
echo 'table creation failure';
}
?>
You can replace you create table line as:-
$sql = "CREATE TABLE ".$dbname.".".$dbtable."".$tablestructure; //NOT CORRECT YET
Also instead of:-
$success = $this->_db->exec($sql);
Use the below lines:-
$stmt = $this->_db->prepare($sql);
$success = $stmt->execute();
Without the above 2 lines, the $succes variable will have value of 0 and although the table can be created, it would echo table creation failed.
Hope this helps.
I am trying to pass an mysqli database connection to a php class. The code I have so far (cut down for simplicity) is as follows:
db.php
$db_host = 'localhost';
$db_name = 'dbname';
$db_user = 'username';
$db_password = 'password';
$db = array('db_host'=>$db_host,
'db_name'=>$db_name,
'db_user'=>$db_user,
'db_password'=>$db_password);
$dbCon = new mysqli( $db['db_host'],
$db['db_user'],
$db['db_password'],
$db['db_name']);
if (mysqli_connect_errno())
{
die(mysqli_connect_error()); //There was an error. Print it out and die
}
index.php
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/db.php");
$sql = "SELECT id FROM usr_clients";
$stmt = $dbCon->prepare( $sql );
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch())
{
$cl = new Client($id, $dbCon);
$cl->doIt();
}
$stmt->close();
}
?>
client.php
<?php
Class Client
{
private $con;
public static $clientCount = 0;
public function __construct( $id, $con )
{
$this->con = $con;
$sql = "SELECT id FROM usr_clients WHERE id = $id";
$stmt = $this->con->prepare( $sql );
if ($stmt)
{
echo "it worked!";
}
else
{
echo "it failed";
}
}
}
?>
Now the index.php page successfully recognises the database connection declared in db.php, and returns a list of all clients. It then loops through each client, and creates a "client" object, passing it the database connection.
It is here that the problem seems to start. In the client class, the database connection is not recognised. I get multiple errors on the page saying "it failed". In the logs, there is a line about calling prepare() on a non object.
Can anyone explain why the connection works in index.php, but not in the client class?
Thanks
Your main problem is assumptions.
You are assuming that there is no connection passed, judging by indirect consequence.
But a programmer should be always logically correct in their reasoning.
Talking of connection? Verify the very connection. var_dump($con) in the constructor. var_dump($this->con) in the method. If it fails - only now you can blame connection and start for the solution.
If not - there is no reason in looking for another connection passing method. Yet it's time to find the real problem.
If your query fails, you have to ask mysql, what's going on, using $this->con->error, as this function will provide you with a lot more useful information than simple "it fails". The right usage I've explained here: https://stackoverflow.com/a/15447204/285587
I'm a .Net developer that have taken over a PHP project. This project has a database layer that looks like this:
<?php
class DatabaseManager {
private static $connection;
const host = "projectname.mysql.hostname.se";
const database = "databaseName";
const username = "userName";
const password = "password";
public function __construct()
{
}
public function instance($_host = null, $_username = null, $_password = null)
{
if(!self::$connection)
{
if(!$_host || !$_username || !$_password)
{
$host = self::host;
$username = self::username;
$password = self::password;
}else{
$host = $_host;
$username = $_username;
$password = $_password;
}
self::$connection = mysql_connect($host, $username, $password);
$this->setDatabase();
}
return self::$connection;
}
public function setDatabase($_database = null)
{
if(!$_database)
{
$database = self::database;
}else{
$database = $_database;
}
$connection = $this->instance();
mysql_select_db($database, $connection) or die(mysql_error());
}
} ?>
I have written a php file that uses this layer but after a while i got these mysql errors implying i didn't close my connections which i hadn't. I try to close them but know i get other weird errors like system error: 111. Very simplyfied my php file looks like this:
<?php
$return = new stdClass();
$uid = '9999999999999';
$return->{"myUid"} = $uid;
$dm = new DatabaseManager();
$dmInstance = $dm->instance();
/* MY CLICKS */
$sql = sprintf("SELECT count(*) as myClicks FROM clicks2011, users2011 WHERE clicks2011.uid = users2011.uid AND users2011.uid = %s AND DATEDIFF(DATE(at), '%s') = 0 AND exclude = 0", mysql_real_escape_string($uid), mysql_real_escape_string($selectedDay));
$result = mysql_query($sql, $dmInstance) or die (mysql_error());
$dbResult = mysql_fetch_row($result);
$return->{"myClicks"} = $dbResult[0];
mysql_close($dmInstance);
echo json_encode($return); ?>
Okay, I'm going to post this as an answer because I think one (possibly both) of these things will help you.
First: You don't need to manually close your MySQL connections. Unless you have set them up so that they persist, they will close automatically. I would avoid doing that unless you determine that every other problem is NOT the solution.
In addition, I would switch to using prepared statements. It's more secure, and pretty future-proof. I prefer PHP's PDO over mysqli, but that's up to you.
If you'd like to look over an example of a simple PDO object to take the many lines out of creating prepared statements and connections and getting results, you can look at my homebrew solution.
Second: "System Error 111" is a MySQL error. From what I've read, it appears that this error typically occurs when you are using PHP and MySQL on the same server, but telling PHP to connect to MySQL via an IP address. Switch your $host variable to 'localhost'. It is likely that this will solve that error.
The problem here is you're calling mysql_close and not specifying a valid mysql connection resource object. You're, instead, trying to close an instance of the DatabaseManager object.
You'll probably want to run mysql_close(DatabaseManager::connection); which is where the DatabaseManager is storing the resource object.
Additionally, I'd personally recommend you learn PDO or use the mysqli drivers. In future releases of PHP the built in mysql functions will be moved into E_DEPRECATED
Try implement __destrcut
public function __destruct()
{
mysql_close(self::$connection)
}
Then simply use unset($dm);