I have tried everything I can possibly think of to get MSSQL to work with WAMP. Here is my code
<?php
$database = "appas";
$conn = new PDO( "sqlsrv:server=(IP) ; Database = $database", "sa1", "Password02");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$conn->setAttribute( PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 1 );
$query = 'select * from user';
// simple query
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row['first'] ."\n" );
}
echo "\n........ query for a column ............\n";
// query for one column
$stmt = $conn->query( $query, PDO::FETCH_COLUMN, 1 );
while ( $row = $stmt->fetch() ){
echo "$row\n";
}
echo "\n........ query with a new class ............\n";
$query = 'select * from user order by last';
// query with a class
class cc {
function __construct( $arg ) {
echo "$arg";
}
function __toString() {
return $this->DepartmentID . "; " . $this->Name . "; " . $this->GroupName;
}
}
$stmt = $conn->query( $query, PDO::FETCH_CLASS, 'cc', array( "arg1 " ));
while ( $row = $stmt->fetch() ){
echo "$row\n";
}
echo "\n........ query into an existing class ............\n";
$c_obj = new cc( '' );
$stmt = $conn->query( $query, PDO::FETCH_INTO, $c_obj );
while ( $stmt->fetch() ){
echo "$c_obj\n";
}
$stmt = null;
?>
I am getting this error
( ! ) Fatal error: Uncaught exception 'PDOException' with message 'could not find driver' in C:\wamp\www\Register\configdb.php on line 3
( ! ) PDOException: could not find driver in C:\wamp\www\Register\configdb.php on line 3
Call Stack
# Time Memory Function Location
1 0.0004 255760 {main}( ) ..\configdb.php:0
2 0.0004 256608 __construct ( ) ..\configdb.php:3
I have no idea why it is not finding the driver - I have the DLL installed i think. I really am grasping at straws here if anyone knows my problem or could link a proper installation guide for MSSQL in WAMP 2.5 that would be fantastic.
http://imgur.com/8T4TasB
Related
I am using PHP PDO prepared statements. I am passing in a string and returning the record from MYSQL. I am passing three variables to the method.
The query returns nothing. If I perform the same query in phpmyadmin it returns all the correct data. I believe it is the ampersand(&) in the $team variable but, don't know I to work around it. I am not using a link and it is not a form element. It is a straight call to the method.
The values of the three parameters are
$season = '2018-19';
$league = 20;
$team = "Texas A&M University-Kingsville";
Here is my method:
public static function getTeamGames($season, $league, $team){
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season &&
league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $team, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}
$weeklyGames = Game::getTeamGames( $season, $league, $tName );
I really appreciate the help of everyone.
Thank you in advance.
I was able to fix the issue.
I had to use html_entity_decode on the $team parameter.
I changed my method to the following:
public static function getTeamGames($season, $league, $team){
$dTeam = html_entity_decode($team);
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season && league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $dTeam, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}
I am They try to use mysqli :: bind_param unsuccessfully . In the code , below , the function login ( ) is called with a username and password on the page login.php . Despite all efforts and guides and forums have read , continues to return the same error .
I tried both with
bind_param ( 's' , $ variable )
that with
bind_param ( 1 , $ variable )
that with
bind_param ( 'ss' , $ variable1 , $ variable2 )
and i tried query without ''
"SELECT id,org_id,org_group_id,people_id FROM users WHERE username = ? AND password = ?"
Where am I wrong ?
public function login($_username, $_password) {
$this->sessionOpen ();
if ($_username == "") {
$this->log->error ( "Username vuoto" );
throw new AuthLoginFailed ();
}
if ($_password == "") {
$this->log->error ( "Password vuota" );
throw new AuthLoginFailed ();
}
$db = new mysqli ( $this->sql ['server'], $this->sql ['username'], $this->sql ['password'], $this->sql ['database'] );
if (mysqli_connect_errno ()) {
$this->log->error ( "Errore di connessione a mysql: " . mysqli_error ( $db ) );
throw new MysqliConnectionError ( "Mysqli error: " . mysqli_error ( $db ) );
}
$stmt = $db->prepare ( "SELECT id,org_id,org_group_id,people_id FROM users WHERE 'username' = ? AND 'password' = ?" );
if (! $stmt) {
$this->log->error ( "Mysqli prepare error: " . mysqli_error ( $db ) );
throw new MysqliPrepareException ( "Mysqli error: " . mysqli_error ( $db ) );
}
echo md5 ( $_username ) . "---" . md5 ( $_password );
//on page username and password is showed at this point
$user=trim(md5 ( $_username ));
$pass=trim(md5 ( $_password ));
$stmt->bind_param ( 1, $user);
$stmt->bind_param ( 2, $pass);
/* Execute it */
$stmt->execute ();
if (! $stmt) {
$this->log->error ( "Mysqli prepare error: " . mysqli_error ( $db ) );
throw new MysqliExecuteException ( "Mysqli error: " . mysqli_error ( $db ) );
}
$stmt->fetch($rst);
echo "results: " . $rst->num_rows; //output of this: results:
if ($rst->num_rows == 0) {
throw new AuthLoginFailed ();
}
/* Close statement */
$stmt->close ();
/* Close connection */
$db->close ();
}
Error in the log of apache is
[Sat Oct 24 08:52:04 2015] [error] [client 192.168.253.6] PHP Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in /www/gexy/XXXX/html/lib/Auth.php on line 77, referer: https://gexy.it/login.php
[Sat Oct 24 08:52:04 2015] [error] [client 192.168.253.6] PHP Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in /www/gexy/XXXX/html/lib/Auth.php on line 78, referer: https://gexy.it/login.php
Many thanks to all
Modification is:
$stmt->bind_param ( "ss", $user, $pass);
because 1 data type is not defind in bind_param (). bind_param() will take two arguments 1st one is types (i, d, s, b) corresponding datatype in your query(?) and 2nd arg are values.
Suggestion's are:
Don't compare with ==, for empty string because if user enter's 3 white spaces it will not equal. use empty() for checking empty string or not.
Don't call unnecessary methods, it does not have any meaning, for eg: in your code your calling trim() after md5(). md5() will not return any white space character. So calling trim(md5($username)) is meaning less.
Try to replace your code with my code hope your problem is solved.
public function login($_username, $_password) {
$this->sessionOpen ();
if (empty($_username)) {
$this->log->error ( "Username vuoto" );
throw new AuthLoginFailed ();
}
if (empty($_password)) {
$this->log->error ( "Password vuota" );
throw new AuthLoginFailed ();
}
$db = new mysqli ( $this->sql ['server'], $this->sql ['username'], $this->sql ['password'], $this->sql ['database'] );
if (mysqli_connect_errno ()) {
$this->log->error ( "Errore di connessione a mysql: " . mysqli_error ( $db ) );
throw new MysqliConnectionError ( "Mysqli error: " . mysqli_error ( $db ) );
}
$stmt = $db->prepare ( "SELECT id,org_id,org_group_id,people_id FROM users WHERE 'username' = ? AND 'password' = ?" );
if (! $stmt) {
$this->log->error ( "Mysqli prepare error: " . mysqli_error ( $db ) );
throw new MysqliPrepareException ( "Mysqli error: " . mysqli_error ( $db ) );
}
echo md5 ( $_username ) . "---" . md5 ( $_password );
//on page username and password is showed at this point
$user=md5 ( $_username );
$pass=md5 ( $_password );
$stmt->bind_param ( "ss", $user,$pass);
/* Execute it */
$stmt->execute ();
if (! $stmt) {
$this->log->error ( "Mysqli prepare error: " . mysqli_error ( $db ) );
throw new MysqliExecuteException ( "Mysqli error: " . mysqli_error ( $db ) );
}
$stmt->fetch($rst);
echo "results: " . $rst->num_rows; //output of this: results:
if ($rst->num_rows == 0) {
throw new AuthLoginFailed ();
}
/* Close statement */
$stmt->close ();
/* Close connection */
$db->close ();
}
Let me know once your problem is solved.
i am having some problem with my code, i try to simple insert some logs when user use search on my site.
Log should contains:
date in unix time -> using function for it
username -> its stored in Session
vin -> its string he post in input field
Top of the class
public $vin = null;
public function __construct( $data = array() )
{
if( isset( $data['vin'] ) )
$this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
public function storeFormValues( $params )
{
$this->__construct( $params );
}
function code:
public function logFromSearch() {
$correct = false;
//$this->username = $_SESSION]['username'];
$date = new DateTime();
try {
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO logs(date, user, vin) VALUES(:date, :user, :vin)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "date", $date->getTimestamp(), PDO::PARAM_STR );
$stmt->bindValue( "user", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
echo $this->vin;
echo $date->getTimestamp();
$stmt->execute();
return "Everything is OKEY";
} catch( PDOException $e ) {
return $e->getMessage();
}
}
Its not importing anything to database dispite the fact it should in my opinion. I try to debug it so i found out my way of adding username from session is not possible way and also find out that this->vin and $date->getTimestamp() is returning actual data which it should insert to database so can somebody help me to find where is the problem? (in same class i am using other function for database connection and they work find so its not in setting up connecting / db name and host and so on because its in different file)
P.S. Errors : I dont get any errors just single notice Notice: Undefined property: Data::$username which is understandable.
I am attempting to set up a class for the simplification of MySQLi queries using the mysqli class. However, when I set up my class to accept an instance of mysqli, I receive this error:
Undefined variable: dbobj in C:\wamp\www\inc\classes\ezsql.class.php on line 93
I've never really done dependency injection before, plus my coding skills aren't with me today, so syntax mistakes might be plentiful.
Here's the class I've created:
<?php
/*/////////////////////////////////////////////////////////////////////////////////////////////
EZSQL
A PHP class that utilizes the PDO MySQLi DB class to make database querying easier and quicker.
/////////////////////////////////////////////////////////////////////////////////////////////*/
class EZSQL {
public $dbobj;
public function __construct( mysqli $dbobject ) {
echo "var_dunp before making this->dbobj\n";
var_dump( $dbobj );
if ( is_object( $dbobject ) ) {
$this->dbobj = $dbobject;
} else {
// Just in case...
die( "EZSQL Error #0: EZSQL must be initialized with a PDO MySQLi DB instance." );
}
echo "var_dunp after making this->dbobj\n";
var_dump( $this->dbobj );
}
public function select( $exp, $table, $where ) {
// Make $where optional
if ( isset( $where ) ) {
$queryString = "SELECT {$exp} FROM {$table} WHERE {$where}";
} else {
$queryString = "SELECT {$exp} FROM {$table}";
}
if ( $returnObj = $this->dbobj->query( $queryString ) ) {
$return = $returnObj->fetch_assoc();
return $return;
} else {
// Some error handling
die( "[EZSQL]: SQL SELECT query error #{$this->dbobj->errno}: {$this->dbobj->error}" );
}
}
public function insert( $tab, $cols, $values ) {
// Create the general query string format
$queryString = "INSERT INTO {$tab} (";
$colsCt = count( $cols );
foreach ( $cols as $key=>$col ) {
if ( $key != ( $colsCt - 1 ) ) {
$queryString .= "{$col}, ";
} else {
$queryString .= "{$col})";
}
}
// More general formatting
$queryString .= " VALUES (";
$valCt = count( $values );
foreach( $values as $key=>$value ) {
if ( $key != ( $valCt - 1 ) ) {
$queryString .= "{$value}, ";
} else {
$queryString .= "{$value})";
}
}
if ( $query = $this->dbobj->prepare( $queryString ) ) {
$query->execute();
} else {
die( "[EZSQL]: SQL INSERT query prepare error #{$this->dbobj->errno}: {$this->dbobj->error}" );
}
}
public function createTable( $name, $ino, $colData ) {
// Create the general query string format
$queryString = "CREATE TABLE";
if ( $ino ) {
$queryString .= " IF NOT EXISTS";
}
$queryString .= " {$name}";
$colCt = count( $colData );
$queryString .= " (";
$iter = 1;
foreach ( $colData as $name=>$type ) {
$iter++;
if ( $iter != ( $colCt ) ) {
$queryString .= " {$name} {$type},";
} else {
$queryString .= " {$name} {$type});";
}
}
if ( !$this->dbobj->query( $queryString ) ) {
die( "[EZSQL]: SQL CREATE TABLE query error #{$this->dbobj->errno}: {$this->dbobj->error}" );
}
}
}
?>
Line 93 is contained inside the function createTable, specifically this if statement:
if ( !$this->dbobj->query( $queryString ) ) {
die( "[EZSQL]: SQL CREATE TABLE query error #{$this->dbobj->errno}: {$this->dbobj->error}" );
}
Any and all help will be greatly appreciated, as I can't quite tell what is wrong.
Again, keep in mind I am new to dependency injection. Syntax errors in PHP are not a rarity for me.
Thanks.
Edit 1: Here's the connection I'm using in my index.php page:
<?php
require( "inc/classes/ezsql.class.php" );
// require( "inc/config.php" );
// require( "inc/proc/db.php" );
$host = "127.0.0.1";
$user = "root";
$pass = "";
$db = "testdb";
$port = "3306";
$db = new mysqli( $host, $user, $pass, $db, $port );
echo "var_dunp before creating instance of EZSQL\n";
var_dump( $db );
if ( !$db ) {
die( "error" );
}
$ezsql = new EZSQL( $db );
$cols = array(
"int" => "int",
"text" => "varchar(255)"
);
$ezsql->createTable( "test1", TRUE, $cols );
?>
Edit 2: Added var_dump()s to certain locations. See this Pastebin for what they return.
Use a pdo wrapper such as this:
http://pastebin.com/AHdJkCBz
Then in the same directory, add settings.ini.php like this http://pastebin.com/cu1kY8kL
Do not commit this settings file to your repository. Copy and paste it always.
The way to call this would be:
function checkPassword($email, $password)
{
$db = new db();
$binding = array('emailId'=>$email, 'hashed_password'=>md5($password));
return $db->single("SELECT id FROM members WHERE pc_address = :emailId AND hashed_password = :hashed_password", $binding);
}
Check the whole class for detailed methods.
I have also made two general purpose functions to add/update database.
function assetsUtilInsert($table, $params, $debug=false){
$db = new db();
if($table && is_array($params)){
$bindings = $params;
if(!empty($bindings)) {
$fields = array_keys($bindings);
$fieldsvals = array(implode(",",$fields),":" . implode(",:",$fields));
$sql = "INSERT INTO ".$table." (".$fieldsvals[0].") VALUES (".$fieldsvals[1].")";
}
if($debug==true)
echo $sql;
$result = $db->query($sql,$bindings);
return $db->lastInsertId();
} else {
assetsUtilInvokeError($this->registry->log, "Could not insert because either table does not exist or parameters is not an array");
}
}
function assetsUtilUpdate($table, $params, $where, $exit=0){
$db = new db();
$sql = '';
if($table && is_array($params) && is_array($where)){
$sql = "UPDATE $table SET ";
foreach($params as $key => $val){
$sql .= $key ."=:$key, ";
}
unset($key); unset($val);
$sql = substr($sql, 0, (strlen($sql)-2));
$sql .= " WHERE ";
foreach($where as $key => $val){
$sql .= $key ."=:$key AND ";
}
unset($key); unset($val);
$bindings = array_merge($params, $where);
unset($params); unset($where);
$sql = substr($sql, 0, (strlen($sql)-4));
if($exit==1){
echo $sql; exit;
}
return $db->query($sql, $bindings);
} else {
assetsUtilInvokeError($this->registry->log, "Could not insert because either table does not exist or params is not an array or where condition is not an array");
}
}
I have used log4php for logging. You could adapt with this code.
Just changing the settings.ini.php for driver can help you use the same code for different databases supported by PDO.
Fixed.
I am an idiot, apparently, and screwed up a few things.
Thanks for the suggestions, but I'm not doing this professionally, so I don't care about injection attacks at this point in time. All of this is hosted locally and not port forwarded, so none of this data really matters.
Input sanitization is next on my list, though.
Check if you have enabled mysqli extension or just test if you can instance outside your class.
Also can we see how you instance and use your class when you get this error.
EDIT
Check mysqli object with var_dump() when you pass to your constructor.
I have an error and I don't know what I am doing wrong. Help, please, with this :)
So, I have a class named Activities and in it a I have few functions as here:
class Activities
{
public $content = null;
public function __construct( $data=array() ) {
if ( isset( $data['content'] ) ) $this->content = $data['content'];
}
public function storeFormValues ( $params ) {
$this->__construct( $params );
}
public static function getData() {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM exceptions WHERE name = 'atrakcje'";
$st = $conn->prepare( $sql );
$st->execute();
$row = $st->fetch();
$conn = null;
if ( $row ) return new Activities( $row );
}
public function update() {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE exceptions SET content=:content WHERE name = 'atrakcje'";
$st = $conn->prepare ( $sql );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->execute();
$conn = null;
}
}
And I have a function editActivities() in my little Admin Panel I made:
function editActivities() {
$results = array();
$results['pageTitle'] = "Edytuj Atrakcje";
$results['formAction'] = "editActivities";
if ( isset( $_POST['saveChanges'] ) ) {
$activities->storeFormValues( $_POST );
$activities->update();
header( "Location: admin.php?action=editActivities&status=changesSaved" );
} elseif ( isset( $_POST['cancel'] ) ) {
header( "Location: admin.php?action=editActivities" );
} else {
$results['activities'] = Activities::getData();
require( TEMPLATE_PATH . "/admin/editActivities.php" );
}
}
Also I have a HTML Form to make changes. But when I submit filled form I get an error:
Fatal error: Call to a member function storeFormValues() on a non-object in C:\xampp\htdocs\admin.php on line 285
285 line in my code is here:
if ( isset( $_POST['saveChanges'] ) ) {
$activities->storeFormValues( $_POST );
$activities->update();
I don't know what's going on. I have just the same code to edit other Articles and Users and I can't figure out what's bad here. Thanks for your help!
$activities is not instantiated, so you can't call one of its instance methods. You ought to instantiate it with
$activities = new Activities($_POST);
Also, in your static function getData you either return an Activities or NULL, depending on the value of $row. But this may make $results['activities'] sometimes an object and sometimes not, which is tricky to handle and might result in the same error being raised again.
add
$activities = new Activities();
$activities->storeFormValues( $_POST );
....