<?php
class CMySQL {
// variables
var $sDbName;
var $sDbUser;
var $sDbPass;
var $vLink;
// constructor
public function CMySQL(){
$this->engine = 'mysql';
$this->host = 'Localhost';
$this->database = 'api';
$this->user = 'root';
$this->pass = '';
$dns = $this->engine.':dbname='.$this->database.";host=".$this->host;
$this->vLink = $dns;
}
// return one value result
function getOne($query, $index = 0) {
if (! $query)
return false;
$res = mysql_query($query);
$arr_res = array();
if ($res && mysql_num_rows($res))
$arr_res = mysql_fetch_array($res);
if (count($arr_res))
return $arr_res[$index];
else
return false;
}
// executing sql
function res($query, $error_checking = true) {
if(!$query)
return false;
$res = $this->vLink;
if (!$res)
$this->error('Database query error', false, $query);
return $res;
}
// return table of records as result in pairs
function getPairs($query, $sFieldKey, $sFieldValue, $arr_type = MYSQL_ASSOC) {
if (! $query)
return array();
$res = $this->res($query);
$arr_res = array();
if ($res) {
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$arr_res[$row[$sFieldKey]] = $row[$sFieldValue];
}
mysql_free_result($res);
}
return $arr_res;
}
// return table of records as result
function getAll($query, $arr_type = MYSQL_ASSOC) {
if (! $query)
return array();
if ($arr_type != MYSQL_ASSOC && $arr_type != MYSQL_NUM && $arr_type != MYSQL_BOTH)
$arr_type = MYSQL_ASSOC;
$res = $this->res($query);
$arr_res = array();
if ($res) {
while ($row = mysql_fetch_array($res, $arr_type))
$arr_res[] = $row;
mysql_free_result($res);
}
return $arr_res;
}
// return one row result
function getRow($query, $arr_type = MYSQL_ASSOC) {
if(!$query)
return array();
if($arr_type != MYSQL_ASSOC && $arr_type != MYSQL_NUM && $arr_type != MYSQL_BOTH)
$arr_type = MYSQL_ASSOC;
$res = $this->res ($query);
$arr_res = array();
if($res && mysql_num_rows($res)) {
$arr_res = mysql_fetch_array($res, $arr_type);
mysql_free_result($res);
}
return $arr_res;
}
// escape
function escape($s) {
return mysql_real_escape_string($s);
}
// get last id
function lastId() {
return mysql_insert_id($this->vLink);
}
// display errors
function error($text, $isForceErrorChecking = false, $sSqlQuery = '') {
echo $text; exit;
}
}
$GLOBALS['MySQL'] = new CMySQL();
?>
I'm learning creating APIs using PHP and wish to convert "mysql_fetch_array and mysql_free_result" to PDO and allow multiple parameters as given. The error am getting for the above code is
mysql_fetch_array() expects parameter 1 to be resource, string given
and
mysql_free_result() expects parameter 1 to be resource, string given
How can I work around this code I came across with..
You are missing the connection logic, I see that you commented this line:
//parent::CMySQL( $dns, $this->user, $this->pass );
However seems that you do not have an parent class for this one.
Check this link
Related
I have written a piece of code for coupon. whenever I use the function to check if the Coupon Code exists, it returns true and prints the statement. But I can't get the false return and cannot get the statement printed for false case.
function db_connect() {
static $connection;
if (!isset($connection)) {
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
}
if ($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection, $query);
return $result;
}
function db_error() {
$connection = db_connect();
return mysqli_error($connection);
}
function db_select($query) {
$rows = array();
$result = db_query($query);
if ($result === false) {
return false;
}
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
function db_rows($query) {
$result = db_query($query);
if ($result === false) {
return false;
}
$total_rows = mysqli_num_rows($result);
return $total_rows;
}
function couponExists($cc) {
$results = db_rows("SELECT * from ms_coupons where coupon_code='".$cc."'") or die(db_error());
if ($results > 0) {
return true;
} else {
return false;
}
}
DB table : ms_coupons
coupon_id coupon_code
1 CODE50
check_coupon.php
$coupon = $_REQUEST['coupon_code'];
if (!couponExists($coupon)) {
echo "Does not exist!";
} else {
echo "Coupon exists!";
}
when i supply coupon_code as CODE50 it prints, Coupon exists! but when i supply something different like CODE51 then the pays prints nothing.
Your problem is with this line in your code:
$results = db_rows("SELECT * from ms_coupons where coupon_code='".$cc."'") or die(db_error());
db_rows function returns number of rows, in your case it can be only two values - 1 or 0. If db_rows return 0 your script executes the die(db_error()) part (but there is no mysqli_error).
Remove the or die(db_error()) part, like this:
$results = db_rows("SELECT * from ms_coupons where coupon_code='".$cc."'");
If you want to check for mysqli_errors, move it to your db_query function.
This Is My Database configuration
It's Extension is Mysql. iwant to change its extension to Mysqli. Help me please.Thanks In Advance.I Want to Change This Because MySQL EXTENSION is no longer available in latest php
class CMySQL {
// variables
var $sDbName;
var $sDbUser;
var $sDbPass;
var $vLink;
// constructor
function CMySQL() {
$this->sDbName = 'YOUR_DB_NAME';
$this->sDbUser = 'DB_USER_NAME';
$this->sDbPass = 'DB_USER_PASS';
// create db link
$this->vLink = mysql_connect("localhost", $this->sDbUser, $this->sDbPass);
//select the database
mysql_select_db($this->sDbName, $this->vLink);
mysql_query("SET names UTF8");
}
// return one value result
function getOne($query, $index = 0) {
if (! $query)
return false;
$res = mysql_query($query);
$arr_res = array();
if ($res && mysql_num_rows($res))
$arr_res = mysql_fetch_array($res);
if (count($arr_res))
return $arr_res[$index];
else
return false;
}
// executing sql
function res($query, $error_checking = true) {
if(!$query)
return false;
$res = mysql_query($query, $this->vLink);
if (!$res)
$this->error('Database query error', false, $query);
return $res;
}
// return table of records as result in pairs
function getPairs($query, $sFieldKey, $sFieldValue, $arr_type = MYSQL_ASSOC) {
if (! $query)
return array();
$res = $this->res($query);
$arr_res = array();
if ($res) {
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$arr_res[$row[$sFieldKey]] = $row[$sFieldValue];
}
mysql_free_result($res);
}
return $arr_res;
}
// return table of records as result
function getAll($query, $arr_type = MYSQL_ASSOC) {
if (! $query)
return array();
if ($arr_type != MYSQL_ASSOC && $arr_type != MYSQL_NUM && $arr_type != MYSQL_BOTH)
$arr_type = MYSQL_ASSOC;
$res = $this->res($query);
$arr_res = array();
if ($res) {
while ($row = mysql_fetch_array($res, $arr_type))
$arr_res[] = $row;
mysql_free_result($res);
}
return $arr_res;
}
// return one row result
function getRow($query, $arr_type = MYSQL_ASSOC) {
if(!$query)
return array();
if($arr_type != MYSQL_ASSOC && $arr_type != MYSQL_NUM && $arr_type != MYSQL_BOTH)
$arr_type = MYSQL_ASSOC;
$res = $this->res ($query);
$arr_res = array();
if($res && mysql_num_rows($res)) {
$arr_res = mysql_fetch_array($res, $arr_type);
mysql_free_result($res);
}
return $arr_res;
}
// escape
function escape($s) {
return mysql_real_escape_string($s);
}
// get last id
function lastId() {
return mysql_insert_id($this->vLink);
}
// display errors
function error($text, $isForceErrorChecking = false, $sSqlQuery = '') {
echo $text; exit;
}
}
$GLOBALS['MySQL'] = new CMySQL();
mysqli has object oriented approach to all the funtions.
for example,
$this->vLink = new mysqli("localhost", $this->sDbUser, $this->sDbPass,$this->sDbName);
But along with the object oriented approach mysqli procedural approach also exists which has just mysqli instead of mysql everywhere. But I personally recommend you to go with the object oriented approach.you can see other important functions along with the old mysql functions here.
My function is always returning false when it should return true, and I can't find why
public function isReselling($key)
{
if ($this->validateKey($key)) {
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
return false;
}
Well, you need to check where exactly the 'return' is beign made, and investigate based on that:
public function isReselling($key)
{
if ($this->validateKey($key)) {
die('validate fails');
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
die('no results.');
return false;
}
and btw, you don't want to have multiple 'returns' around the code, that's bad practice.
I would change your code to something like:
public function isReselling($key)
{
$retValue = false;
if ($this->validateKey($key) === false) {
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "SELECT * FROM api_id";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
if ($row['Banned'] == 1) {
$retValue = true;
break;
}
}
}
return $retValue;
}
I am using the following method to query from my SQL database:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = (what goes here?)
I am trying to get the string name from users, how can I do this?
If your query is right then
try this:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = $result['result'][0]['name'];
You forgot to pass the value to the function
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1")
$name = "";
if(! isset($result["error"]) and isset($result["name"])) // check it returns error or not. then check name field exist or not.
{
$name = $result["name"];
}
echo $name;
I have inherited the below code, which creates a web interface for a MySQL database named 'database_name' and defined by the variable $database.
I want to add an additional database to this script, so that the same interface can be created this second database (which is set up in exactly the same way as the first database with the same tables names, etc., but contains different data). Is there a way to make $database a string array which I can loop over for multiple database names?
<?php
class DatabaseInterface {
public $host = "localhost"; //(name or ip address)
public $userName = "aksfhah";
public $passWord = "**********";
public $database = 'database_name';
public $tableData = "measurements";
public $tableMinbins = "minbins";
public $tableHourbins = "hourbins";
public $tableDaybins = "daybins";
public $tableDescriptions = "measurementDescriptions";
public $tableSpecs = "experimentDescriptions";
public $connection;
public function __construct($databaseName = "database_name") {
$this->database = $databaseName;
$this->connect();
}
public function connect($databaseName = null) {
$dbh = mysql_connect($this->host, $this->userName, $this->passWord);
if (is_null($databaseName)) {
mysql_select_db($this->database);
} else {
mysql_select_db($databaseName);
}
$this->connection = $dbh;
return $dbh;
}
public function initializeDatabase() {
$this->createDataTable($this->tableData);
$query = "create table if not exists $this->tableDescriptions (id int auto_increment primary key,type varchar(255),
description varchar(255), experimentname varchar(255), unique Key(description,experimentname)) engine=myisam";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
private function createDataTable($tableName) {
$query = "CREATE TABLE IF NOT EXISTS $tableName (
id smallint(5) unsigned NOT NULL,
time datetime NOT NULL,
measurement float DEFAULT NULL,
rebinned tinyint(4) DEFAULT '0',
PRIMARY KEY (id,time),
KEY (rebinned,id)
) ENGINE=MyISAM";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
public function insertByDescription($time, $value, $channelDescription, $experimentDescription, $type = "other") {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertById($time, $value, $sensorID);
}
public function insertMultipleById($timeArray, $valueArray, $sensorID,$tableName=null) {
if(is_null($tableName)){
$tableName= $this->tableData;
}
if (count($timeArray) == 0)
return 0;
$query = "insert ignore into $tableName (id,time,measurement)
VALUES ";
for ($index = 0; $index < count($timeArray); $index++) {
$timeString = $timeArray[$index]->format("Y-m-d H:i:s");
$value = $valueArray[$index];
$query = $query . "('$sensorID','$timeString','$value'),";
}
$query = substr($query, 0, strlen($query) - 1); //trim final comma
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else
return mysql_affected_rows();
}
public function insertMultipleByDescription($timeArray, $valueArray, $channelDescription, $experimentDescription, $type = "other",$tableName=null) {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertMultipleById($timeArray, $valueArray, $sensorID,$tableName);
}
public function insertById(DateTime $time, $value, $sensorID) {
$timeString = $time->format("Y-m-d H:i:s");
$query = "insert ignore into $this->tableData (id,time,measurement)
VALUES ('$sensorID','$timeString','$value')";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else if (mysql_affected_rows() == 0) {
return false;
} else {
return true;
}
}
public function createIdFromDescription($channelDescription, $experimentDescription, $type) {
$sensorId = $this->getIdFromDescription($channelDescription, $experimentDescription);
if (!$sensorId) {
$query = "insert ignore into $this->tableDescriptions (description,experimentname,type)
VALUES ('$channelDescription','$experimentDescription','$type')";
$result = mysql_query($query);
$sensorId = mysql_insert_id();
}
return $sensorId;
}
public function getIdFromDescription($measurementDescription, $experimentDescription) {
$sensorId = false;
$query = "select id from $this->tableDescriptions where description like '$measurementDescription'
&& experimentname like '$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$sensorId = $row['id'];
}
return $sensorId;
}
function getDataById($id, $startDate, $endDate, $interval = "") {
$data = array();
$startDateString = $startDate->format("Y-m-d H:i:s");
$endDateString = $endDate->format("Y-m-d H:i:s");
$query = "select time,measurement from $this->tableData where id='$id' && time>='$startDateString' && time <='$endDateString' order by time asc " . $interval = "" ? "" : "group by $interval";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
//$time = new DateTime($row['time']);
$data[] = array($row['time'], $row['measurement'] * 1);
}
return $data;
}
public function getMostRecentData($id, $table) {
$query = "select date(max(time)) as time,measurement from $table where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
} elseif (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
return $row;
} else {
return false;
}
}
public function getExperimentList() {
$list = array();
$query = "select distinct experimentname from $this->tableDescriptions";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[] = $row['experimentname'];
}
return $list;
}
public function getChannelList($experimentDescription) {
$list = array();
$query = "select id,description,type from $this->tableDescriptions where experimentname='$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[$row['description']] = array("id" => $row['id'], "type" => $row['type']);
}
return $list;
}
public function getDescriptionFromId($id) {
$query = "select * from $this->tableDescriptions where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_fields($result) > 0) {
$row = mysql_fetch_array($result);
return array($row['type'], $row['description'], $row['experimentname']);
} else {
return false;
}
}
public function getDisplayName($experimentName) {
$query = "select displayName from $this->tableSpecs where experimentName='$experimentName'";
$result = mysql_query($query);
echo mysql_error();
$row = mysql_fetch_array($result);
if ($row) {
return $row['displayName'];
} else {
return false;
}
}
public function simpleQuery($query) {
$result = mysql_query($query);
echo mysql_error();
if ($result) {
$row = mysql_fetch_array($result);
if ($row) {
return $row[0];
} else {
return FALSE;
}
} else {
return FALSE;
}
}
public function rebin($tableSource, $tableTarget, $numSeconds, $sum = false) {
$this->createDataTable($tableTarget);
echo "Updating $tableSource to set rebinned from 0 to 2...";
$query = "update $tableSource set rebinned=2 where rebinned =0;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
$numRows = mysql_affected_rows();
echo "Found $numRows records in $tableSource that need rebinning...\n";
$query = "select id,from_unixtime(floor(unix_timestamp(min(time))/$numSeconds)*$numSeconds) as mintime from $tableSource where rebinned=2 group by id;";
$result = mysql_query($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$mintime = $row['mintime'];
echo $id . "...";
$query = "INSERT INTO $tableTarget (id,time,measurement,rebinned)
SELECT id,from_unixtime(floor(unix_timestamp(time)/$numSeconds)*$numSeconds)," . ($sum ? "sum" : "avg") . "(measurement) as measurement,0
FROM $tableSource WHERE id=$id && time>='$mintime'
GROUP BY id,floor(unix_timestamp(time)/$numSeconds)
ON DUPLICATE KEY UPDATE measurement=values(measurement), rebinned=0;";
mysql_query($query);
//echo $query;
echo mysql_error();
echo "Done.\n";
}
echo "Updating $tableSource to set rebinned from 2 to 1...";
$query = "update $tableSource set rebinned=1 where rebinned =2;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
}
}
public function getDCPower($experimentName, $startDate, $endDate) {
$out = array();
$query = $this->buildDCPowerQuery($experimentName, $this->tableMinbins);
if ($query) {
if ($startDate != "") {
$query = $query . " && m0.time>='$startDate' ";
}
if ($endDate != "") {
$query = $query . " && m0.time<='$endDate' ";
}
echo $query;
$result = mysql_query($query);
echo mysql_error();
while ($row = mysql_fetch_array($result)) {
// echo $row['time'].", ".$row['power']."\n";
$out[] = array($row['time'], $row['power'] + 0);
}
return $out;
} else {
return FALSE;
}
}
}
?>
Is there a way to make $database a string array which I can loop over for multiple database names?
No, it does not work that way. The script you have defines a class. You have to look in the file that uses that class, where there will be something like
$interface = new DatabaseInterface("database1");
There you'll be able to do things such as
$interface = array();
$interface[0] = new DatabaseInterface("database1");
$interface[1] = new DatabaseInterface("database2");
and use two instances of the interface against the two databases.