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;
Related
Basically I'm trying to show a display message depending on if the row within a database was changed or not, I've looked around and it was suggested to use rowCount which I did, however it's still showing me the wrong output
function makeActive()
{
try{
$database = new Database;
$text = "";
$activecode = $_GET["activecode"];
$setActive = "UPDATE username SET active = '1', activecode = 'Active' WHERE activecode = :activecode";
$stmt = $database->query($setActive);
$database->bind(':activecode', $activecode);
$database->execute();
$update = $database->rowCount();
if ($update === 1)
{
return $text .="Your account is now active" . "<br><a href='index.php'>Home page</a>";
}
else
{
return $text .="Your account is already active" . "<br><a href='index.php'>Home page</a>";
}
}
catch(Exception $e )
{
return $text .= "Something went wrong contact site administrator" . "<br><a href='index.php'>Login page</a>";
header( "refresh:10; url=index.php" );
}
}
So basicaly what should happen is if a row is updated, it should display return $text .="Your account is now active" . "<br><a href='index.php'>Home page</a>";
Added database class
class Database
{
private $host = "localhost";
private $user = "root";
private $pass = "";
private $dbname = "got";
private $dbh;
private $error;
private $stmt;
public function __construct()
{
//SET DSN
$dsn = "mysql:host=". $this->host . ";dbname=" . $this->dbname;
$options = array
(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE =>PDO::ERRMODE_EXCEPTION
);
//create PDO
try
{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
catch(PDOEception $e)
{
$this->error = $e->getMessage();
}
}
public function query($query)
{
$this->stmt = $this->dbh->prepare($query);
}
public function bind($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;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute()
{
return $this->stmt->execute();
}
public function lastInsertId()
{
$this->dbh->lastInsertId();
}
public function rowCount()
{
$this->stmt->rowCount();
}
public function connect()
{
$this->dbh->connect();
}
public function resultset()
{
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
Here it is the problem:
Replace the method:
public function rowCount()
{
$this->stmt->rowCount();
}
with this:
public function rowCount()
{
return $this->stmt->rowCount();
}
I would like to create a PDO function where I can pass a variable to it and get the result shown below.
The variable I would like to pass is called $range.
I would like to call the function by:
$range=$row["part_number"];
function get_range($range);
Then to get the result show below:
<?php
$range = "gmb3-30";
include ("order/connection.php");
// --------------------- Connect to the table-------------------------
$stmt = $pd->prepare('SELECT * FROM mytable WHERE part_number = :part_number');
$stmt->execute(array(
':part_number' => $range
));
$row = $stmt->fetch(PDO::FETCH_BOTH);
echo " <select name=select>";
$c = $row["price_each1"]; // price for single item
for ($i = 1; $i <= 8; $i++)
{
$b = $row["price_each" . $i];
if ($b != 0.00)
{
$d = (($c - $b) / $c) * 100;
$complete = $row[("price_break" . $i) ] . " ," . round($d) . "%";
echo "<option> ";
echo $complete . "</option>";
}
}
echo “ < / select > ”;
?>
Create a class like this and include it:
<?php
class Database{
// Define configuration
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
// Declare a new variables at the top of your class for the Database Handler and any errors.
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname.';charset=utf8;';
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($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;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function simpleSingle(){
$this->execute();
//$this->stmt->fetch(PDO::FETCH_ASSOC);
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->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
Then replace your code by this one:
function get_range($range) {
$database = null;
$database = new Database();
$database->query("SELECT * FROM mytable WHERE part_number = :part_number;");
$database->bind(':part_number', $range);
$row = $database->resulset();
if (!$row) {
// Do whatever needs to be done when you get no results
die();
} else {
echo " <select name=select>";
$i = 0;
foreach ($row as $option) {
if ($i <= 8){
$b=$option["price_each"];
if ($b !=0.00)
{
$d=(($c-$b)/$c)*100;
$complete=$option[("price_break"]. " ," .round($d)."%";
echo "<option> ";
echo $complete ."</option>";
}
$i = $i + 1;
}
}
echo “</select>”;
}
}
And in the end, call the function:
$range=$row["part_number"];
function get_range($range);
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"
Hello I'm trying to make a code to UPDATE or EDIT the survey answers and comments per answer but when I execute the function submiting the form, it did not save any value into the database. What can I do to fix it?
I'm new in PDO.
Thanks in advance.
Database Structure
"Questions" (idquestion, question)
"Surveys" (idsurvey, idquestion, answers, comments_per_question, survey_number)
Update function
public function ModifySurveyMulti($answer = array())
{
if(!empty($answer)) {
foreach($answer as $questi => $value ) {
$this->MyDB->Write("UPDATE survey SET(
`idquestion` = '".$questi."',
`answers` = '".$value[0]."',
`comments_per_answer`= '".$_POST["comment"][$questi]."')");
}
}
}
modify_surveyform.php
<th><?php echo $row["questions"];?></th>
<td>
<input type = "text"
name = "answer[<?php echo $row['idquestion'];?>][]"
value = "<?php echo $row["answers"];?>">
</input>
</td>
<td>
<Textarea type = "text"
name = "comment[<?php echo $row['idquestion'];?>]"
cols = "50" rows = "3"/> <?php echo $row["comment"];?
</textarea>
</td>
</tr><?php } ?>
Mydbconnect.php
<?php
// I'm adding my PDO database because yours is deprecated
class DBConnect
{
public $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;
dbname=$db",$user,
$pass, array(
PDO::ATTR_ERRMODE
=> PDO::ERRMODE_WARNING
)
);
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
while($array = $query->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $array;
}
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}?>
Few things you need to do:
First of all ditch this code, it is useless and expose you to sql
injection
Use PDO directly with prepared statement
The query you need is :
UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?) WHERE idquestion = ?
You will need to adjust your class to only create the connection
class DBConnect
{
public $con;
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO(
"mysql:host=$host;dbname=$db",
$user,$pass,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING)
);
}
catch (Exception $e) {
die($e);
}
}
public function get_connection(){
return $this->con;
}
}
So that you can create it like this:
$db = new DBConnect(/*pass arguments here*/);
$this->MyDB = $db->get_connection();
Modify and use it in your function:
public function ModifySurveyMulti($answer = array(), $comments)
{
$sql = 'UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?)
WHERE idquestion = ?';
$stmt->prepare($sql);
foreach($answer as $questi => $value ) {
$stmt->execute(array($value, $comments[$questi],$questi));
$count = $stmt->rowCount();
echo $count > 0 ? $questi.' updated' : $questi.' did not update';
}
}
Call the function :
if(isset($_POST['answer'], $_POST['comments'])){
$answers = $_POST['answer'];
$comments = $_POST['comments'];
ModifySurveyMulti($answers, $comments);
}
We've just updated PHP on our server, for the most part everything is fine, but the mssql_ functions aren't supported any more unfortunately. I've tried to update our previous class:
$connection['server'] = 'server, port';
$connection['user'] = 'user';
$connection['pass'] = 'pass';
$connection['db'] = 'db';
class mssqlClass {
function connect($dbhost = NULL){
global $connection;
if(! ISSET ($dbconnect)){
$dbconnect = mssql_Connect($connection['server'], $connection['user'], $connection['pass'], true);
}
if(! $dbconnect){
return 'Failed to Connect to Host';
}else{
$select = mssql_select_db($connection['db'], $dbconnect);
if(! $select){
return 'Failed to select Database';
}else{
return $dbconnect;
}
}
}
function getData ($query){
$this->data_array = array();
$result = mssql_query($query);
while ($row = mssql_fetch_assoc($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query){
$result = mssql_query($query) or die("Query didn't work");
}
}
To be compliant with sqlsrv_, and whilst I can connect to the database without any issues, it won't return any data!:
class mssqlClass {
function connect($database = 'Db') {
$mssql_server = 'server';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
if(! ISSET ($dbconnect)){
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
}
if(! $dbconnect){
return 'Failed to connect to host';
}
}
function getData ($query) {
$result = sqlsrv_query($db->connect, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
}
ps. Example usage is as follows:
$db = new mssqlClass();
$conn = $db->connect('DATABASE');
$query = "SELECT * FROM Table";
$result= $db->getData($query);
So sorry for the horrible amount of code - I can edit it down to just the getData function if that's easier? Thank you!!
I've made some changes in your class:
<?php
class mssqlClass {
protected $connection = null;
public function connect($database = 'Db') {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($this->connection, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work..");
}
}
The code looks fine. The only thing which could be your problem is that sqlsrv_fetch_array needs maybe a second parameter e.g.:
sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Because the default is that it returns two arrays with different formats. And if you may acess attributes by name it will return nothing but not fail.
Something like this. Because you actually call the sqlsrv_query method with the return value of the following method. And in the original version you missed to return the connection resource.
function connect($database = 'Db') {
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
return $dbconnect;
}
in advance
function getData ($query) {
$result = sqlsrv_query($db->connect(), $query);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
I found this page while trying to find a quick short-cut to someone else's wrapper class for sqlsrv commands. Since this wasn't really complete, I have compiled my own quickly. Please don't think this is production code, you should test and test again, but it might help someone out of a jam quickly.
class db {
protected $connection = null;
private $debug = true;
private $stmt = null;
private $insertid = null;
private $affectedrows = null;
public function db($host = '.',$database,$username,$password) {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
// data for making connection
$sqlsvr_details = array( 'UID' => $username,
'PWD' => $password,
'Database' => $database,
'CharacterSet' => 'UTF-8'
);
// try to connect
$this->connection = sqlsrv_connect($host, $sqlsvr_details);
if($this->connection == false){
$this->debug('Failed to connect to host: '.$this->errors(),true);
return false;
}else{
return true;
}
}
public function query($query) {
return new resultset($query,$this->connection,$this->debug);
}
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
public function delete($query){
return $this->update($query);
}
public function update($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
$this->affectedrows = #sqlsrv_rows_affected($this->stmt);
return $this;
}
}
public function insert($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
//Get the last insert ID and store it on here
$this->insertid = $this->query('select ##IDENTITY as insert_id')->asObject()->insert_id;
return $this;
}
}
public function insert_id(){
return $this->insertid;
}
public function affected_rows(){
return $this->affectedrows;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}
class resultset implements Countable,Iterator {
private $result = null;
private $connection = null;
private $debug = false;
private $internal_pointer = 0;
private $data = array();
public function resultset($query,$link,$debug = false){
$this->connection = $link;
$this->debug = $debug;
$this->result = sqlsrv_query($this->connection, $query, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
if ($this->result == false){
$this->debug('Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
return $this;
}
}
public function asObject($step = true){
$object = sqlsrv_fetch_object($this->result,NULL,NULL,SQLSRV_SCROLL_ABSOLUTE,$this->internal_pointer);
if (! $object){
return false;
}else{
if ($step) $this->internal_pointer++;
return $object;
}
}
public function num_rows() {
return sqlsrv_num_rows($this->result);
}
public function free(){
$this->internal_pointer = 0;
if (is_resource($this->result)){
sqlsrv_free_stmt($this->result);
}
}
public function __destory(){
$this->free();
}
//Countable Function
public function count(){
return $this->num_rows();
}
//Iteration Functions
public function rewind(){
$this->internal_pointer = 0;
}
public function current(){
return $this->asObject(false);
}
public function key(){
return $this->internal_pointer;
}
public function next(){
$this->internal_pointer++;
}
public function valid(){
return $this->internal_pointer <= $this->num_rows();
}
//============================================
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}