I have a filling form that's work fine.Until recently a user complained of duplicate values being saved in database.Table Lts is related to table2 Koleks in a one to many relationship
action
public function executeKolect(sfWebRequest $r){
$areaId = //code;
$this->lts = Doctrine_Core::getTable('Lts')->getPaid($areaId, $this->selectedLot);
if($r->isMethod('post')) {
//code
}
foreach($this->lts as $l) {
$amount = $r->getParameter('amount_received_'.$l['id']);
$dateOfPayment = $r->getParameter('date_of_payment_'.$l['id'], date('Y-m-d'));
$startPayment = $l['date_start_of_payment'];//date_of_payment should not less than date_start_of_payment
$collectionsTable = Doctrine_Core::getTable('Koleks')->getDateCreate($l['id'],$dateOfPayment);
//here i want to make a method to check if the date_of_payment value that i want to insert does not exist yet in the Koleks table related to Lts table
$koleksTable = Doctrine_Core::getTable('Koleks')->getDateCreate($l['id'],$dateOfPayment);
if ($koleksTable >0) {
$this->fieldErrors['date_of_payment_'.$l['id']] = 'exist';
}
else {
//code ..proceed
}
}
now in doctrine table
public function getDateCreate($loanId,$datePayment) {
$q = $this->createQuery('k')
//->select('k.date_created')
// ->from('Koleks k')
->innerJoin('k.Lts l')
->where('k.l_id=?',$loanId)
->andWhere('k.date_created=?',$datePayment);
//return $q->count();
$dateCreate = $q->count();
if ($dateCreate == 1) {
$res = $q->fetchAll();
return $res;
}
else {
return $dateCreate;
}
}
I want to return an error if a same 'date_created' value is already exist in a Koleks table
But this code will not work..
In my previous project,Using mysqli, I can easily 'avoid' duplicates by using this code
//Action
$collectionsTable=$link->getdateCreated($date,$id)
if $collectionsTable > 0 {
echo "cant proceed"
}
else {
//code to proceed
}
//in myclass.php
$date = _POST//
function getDateCreate($date) {
$query = $this->link->query("SELECT date_created FROM Koleks WHERE date_created = '$date'");
$rowcount = $query->rowCount();
if($rowcount == 1)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowcount;
}
}
I think your code in the Doctrine Table should be (double check the aliases)
public function getDateCreate($loanId,$datePayment) {
$q = $this->createQuery('k')
->innerJoin('k.Lts l')
->andWhere('k.l_id = ?',$loanId)
->andWhere('k.date_created = ?',$datePayment);
return $q;
}
and in your action
//[...]
$koleksTable = Doctrine_Core::getTable('Koleks')->getDateCreate($l['id'],$dateOfPayment);//GET THE QUERY
$koleksTable->execute(); //EXECUTE THE QUERY
if ($koleksTable->count() >0) {
$this->fieldErrors['date_of_payment_'.$l['id']] = 'exists';
}
else
{
//code ..proceed
}
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;
}
My code always return "true" whatever the string is I tried a bunch of thing but they are only return false... I have no idea what I can do to fix this... my code:
public function isBlacklisted($string)
{
$apis = mysql_connect("mysql.hostinger.fr", "mysql user", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "SELECT * FROM blacklist";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
if (strpos($string,$username) !== 0) {
return true;
break;
} else {
return false;
break;
}
}
}
strpos returns false is it is not found, and 0 if it is in the first position of the string. It sounds like you want to do:
if (strpos($string,$username) !== false) {
Also, you are looping over the DB results, you should only return if it is found:
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
if (strpos($string,$username) !== false) {
return true;
}
}
return false;
Or, even better:
$sql = "SELECT * FROM blacklist WHERE 'username' LIKE '%$username%'";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
if ($row['username']) return true;
}
making sure to escape $username and ideally switching to mysqli or pdo instead of using deprecated mysql statements.
I have reproduced this function:
function getTables()
{
global $db;
$value = array();
if (!($result = $db->query('SHOW TABLES'))) {
return false;
}
while ($row = $db->fetchrow($result)) {
if (empty($this->tables) or in_array($row[0], $this->tables)) {
$value[] = $row[0];
}
}
if (!sizeof($value)) {
$db->error("No tables found in database");
return false;
}
return $value;
}
in this manner:
public function getTables() {
$value = array();
$tables = array();
$sql = "SHOW TABLES";
if($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
while( $row = $stmt->fetch_row() ) {
if(empty($tables) or in_array($row[0], $tables)) {
$value[0] = $row[0];
}
}
$stmt->close();
if(!sizeof($value)) {
echo 'The database has no tables';
}
return $value;
} else {
echo 'Couldn\t query the database';
}
}
But the second method returns me The database has no tables which is not true because I have one table in the db.
What is it wrong with the second method ?
In case you wonder what connect does :
public $connect;
public function __construct() {
// Define The Database Connection Or Die If Failed Connecting
$this->connect = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(DB_CONNECTION_ERROR_MESSAGE);
}
It make a connection with the database. And prepare() it's a mysqli statement. I tried with query() too, same result.
Correct code. Use query instead of prepare:
public function getTables()
{
$value = array();
$tables = array();
$sql = "SHOW TABLES";
if ($res = $this->connect->query($sql))
{
while ($row = $res->fetch_row())
{
if (empty($tables) or in_array($row[0], $tables))
{
$value[] = $row[0];
}
}
if (!sizeof($value))
{
echo 'The database has no tables';
}
return $value;
}
else
{
echo 'Could not query the database';
}
}
If you still want to use prepare then you will also need $stmt->bind_result and $stmt->fetch() instead of fetch_row.
I think this piece of code is broken
$value[] = $row[0];
and probably you should change it to
$value[0] = $row[0]; or array_push($value, $row[0])
I'm writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions.
I want somebody who can go through this simple script and let me know where I am making my mistake.
This is my class.connect.php:
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
This is my index.php:
<?php
require_once ("class.connect.php");
$connection = new mySQL();
$connection->connect('localhost', 'myDB', 'joker', 'names_list');
$myquery = "SELECT * FROM list";
$query = $connection->query($myquery);
while($array = $connection->fetch($query))
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
I am getting the error saying that Error querying the Database.
Few problems :-
you don't die without provide a proper mysql error (and is good practice to exit gracefully)
fetch method is only FETCH the first row
mysqli have OO method, why you still using procedural function?
The problem is either this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
or this:
while($array = $connection->fetch($query))
Because you are using the result from the query to query again. Basically, you are doing:
$r = mysqli_query($this->dbc, $sql);
$array = mysqli_fetch_array(mysqli_query($this->dbc, $r));
And you are getting an error, because $r is not a query string. When it's converted to a string, it's a "1" (from your other comment).
Try changing the function to (changed name of variable so you can see the difference):
public function fetch($result)
{
return mysqli_fetch_array($result);
}
or just call the function directly.
If you don't do your own db abstraction for learning php and mysql, you can use Medoo (http://medoo.in/).
It's a free and tiny db framework, that could save a huge work and time.
Obviously an error occurs on SELECT * FROM list you can use mysqli_error to find the error:
return mysqli_query($this->dbc, $sql) or die('Error:'.mysqli_error($this->dbc));
This will display the exact error message and will help you solve your problem.
Try to check this
https://pramodjn2.wordpress.com/
$database = new db();
$query = $database->select(‘user’);
$st = $database->result($query);
print_r($st);
class db {
public $server = ‘localhost';
public $user = ‘root';
public $passwd = ‘*****';
public $db_name = ‘DATABASE NAME';
public $dbCon;
public function __construct(){
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db_name);
}
public function __destruct(){
mysqli_close($this->dbCon);
}
/* insert function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
*/
public function insert($table,$values)
{
$sql = “INSERT INTO $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}else{
return false;
}
$this->dbCon->query($sql) or die(mysqli_error());
return mysqli_insert_id($this->dbCon);
}
/* update function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
$condition = array(‘id’ =>5,’first_name’ => ‘pramod!’);
*/
public function update($table,$values,$condition)
{
$sql=”update $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}
$k=0;
if(!empty($condition)){
foreach($condition as $key=>$val){
if($k==0){
$sql .= ” WHERE $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$result = $this->dbCon->query($sql) or die(mysqli_error());
return $result;
}
/* delete function table name, array value
$where = array(‘id’ =>5,’first_name’ => ‘pramod’);
*/
public function delete($table,$where)
{
$sql = “DELETE FROM $table “;
$k=0;
if(!empty($where)){
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$del = $result = $this->dbCon->query($sql) or die(mysqli_error());
if($del){
return true;
}else{
return false;
}
}
/* select function
$rows = array(‘id’,’first_name’,’last_name’);
$where = array(‘id’ =>5,’first_name’ => ‘pramod!’);
$order = array(‘id’ => ‘DESC’);
$limit = array(20,10);
*/
public function select($table, $rows = ‘*’, $where = null, $order = null, $limit = null)
{
if($rows != ‘*’){
$rows = implode(“,”,$rows);
}
$sql = ‘SELECT ‘.$rows.’ FROM ‘.$table;
if($where != null){
$k=0;
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}
if($order != null){
foreach($order as $key=>$val){
$sql .= ” ORDER BY $key “.htmlentities($val, ENT_QUOTES).””;
}
}
if($limit != null){
$limit = implode(“,”,$limit);
$sql .= ” LIMIT $limit”;
}
$result = $this->dbCon->query($sql);
return $result;
}
public function query($sql){
$result = $this->dbCon->query($sql);
return $result;
}
public function result($result){
$row = $result->fetch_array();
$result->close();
return $row;
}
public function row($result){
$row = $result->fetch_row();
$result->close();
return $row;
}
public function numrow($result){
$row = $result->num_rows;
$result->close();
return $row;
}
}
The mysqli_fetch_array function in your fetch method requires two parameters which are the SQL result and the kind of array you intend to return. In my case i use MYSQLI_ASSOC.
That is it should appear like this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql), MYSQLI_ASSOC);
return $array;
}
**classmysql.inc.php**
<?php
class dbclass {
var $CONN;
function dbclass() { //constructor
$conn = mysql_connect(SERVER_NAME,USER_NAME,PASSWORD);
//$conn = mysql_connect(localhost,root,"","");
if(!$conn)
{ $this->error("Connection attempt failed"); }
if(!mysql_select_db(DB_NAME,$conn))
{ $this->error("Database Selection failed"); }
$this->CONN = $conn;
return true;
}
//_____________close connection____________//
function close(){
$conn = $this->CONN ;
$close = mysql_close($conn);
if(!$close){
$this->error("Close Connection Failed"); }
return true;
}
function error($text) {
$no = mysql_errno();
$msg = mysql_error();
echo "<hr><font face=verdana size=2>";
echo "<b>Custom Message :</b> $text<br><br>";
echo "<b>Error Number :</b> $no<br><br>";
echo "<b>Error Message :</b> $msg<br><br>";
echo "<hr></font>";
exit;
}
//_____________select records___________________//
function select ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^select",$sql)){
echo "Wrong Query<hr>$sql<p>";
return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if((!$results) or empty($results)) { return false; }
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results)) {
$data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
//________insert record__________________//
function insert ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^insert",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if(!$results){
$this->error("Insert Operation Failed..<hr>$sql<hr>");
return false; }
$id = mysql_insert_id();
return $id;
}
//___________edit and modify record___________________//
function edit($sql="") {
if(empty($sql)) { return false; }
if(!eregi("^update",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
$rows = 0;
$rows = #mysql_affected_rows();
return $rows;
}
//____________generalize for all queries___________//
function sql_query($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
if(!eregi("^select",$sql)){return true; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
function extraqueries($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
}
?>
**config.inc.php**
<?php
ini_set("memory_limit","70000M");
ini_set('max_execution_time', 900);
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
############################################
# Database Server
############################################
if($_SERVER['HTTP_HOST']=="localhost")
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
else
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
#############################################
# File paths
#############################################
// For the Database file path
include("system/classmysql.inc.php");
//For the inc folders
define("INC","inc/");
//For the Function File of the pages folders
define("FUNC","func/");
//For the path of the system folder
define("SYSTEM","system/");
$table_prefix = 'dep_';
################################################################
# Database Class
################################################################
$obj_db = new dbclass();
?>
**Function Page**
<?php
// IF admin is not logged in
if(!isset($_SESSION['session_id']))
{
header("location:index.php");
}
$backpage = 'page.php?type=staff&';
if(isset($_REQUEST['endbtn']) && trim($_REQUEST['endbtn']) == "Back")
{
header("location:".$backpage);
die();
}
// INSERT into database.
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")
{
$pass = addslashes(trim($_REQUEST['password']));
$password = encrypt($pass, "deppro");
$username = addslashes(trim($_REQUEST['username']));
$sql = "select * from ".$table_prefix."users where `UserName` ='".$username."'";
$result = $obj_db->select($sql);
if(count($result) == 0)
{
$insert="INSERT INTO ".$table_prefix."users (`UserName`)VALUES ('".$username."')";
$sql=$obj_db->insert($insert);
$newuserid = mysql_insert_id($obj_db->CONN);
}
header("location:".$backpage."msg=send&alert=2");
die();
}
// DELETE record from database
if(isset($_REQUEST['action']) && trim($_REQUEST['action'])==3)
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
$sql_del = "Delete from ".$table_prefix."users where StaffID ='$id'";
$del = $obj_db->sql_query($sql_del);
header("location:".$backpage."msg=delete&alert=2");
die();
}
}
// UPDATE the record
$action=1;
if((isset($_REQUEST['action']) && trim($_REQUEST['action'])==2) && (!(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")))
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
//$id = $_SESSION['depadmin_id'];
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$title = stripslashes($row['StaffTitle']);
$action=2;
}
}
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Update")
{
$title = addslashes(trim($_REQUEST['title']));
$sql_upd ="UPDATE ".$table_prefix."users SET `StaffTitle` = '$title' WHERE StaffID ='$id'";
$result = $obj_db->sql_query($sql_upd);
$action=1;
header("location:".$backpage."msg=edited&alert=2");
die();
}
}
}
if(isset($_REQUEST['vid']) && trim($_REQUEST['vid']!=""))
{
$id = site_Decryption($_REQUEST['vid']);
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$username = stripslashes($row['UserName']);
}
}
}
?>
<td class="center"><span class="editbutton"> </span> <span class="deletebutton"> </span> <a class="lightbox" title="View" href="cpropertyview.php?script=view&vid=<?php echo site_Encryption($sql[$j]['PropertyID']); ?>&lightbox[width]=55p&lightbox[height]=60p"><span class="viewbutton"> </span></a></td>