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.
So I have a function within a class to take the highest value based on another value but I'm getting a blank page.
I checked for bad syntax but there's none that the validator found and if I change it to header("Location: https://facebook.com") it will go to the site so it seems the function is working. However I am not getting my variable back.
My connections and everything else are fine as my other functions in this class return what I want.
class FORUM
{
private $forum;
function __construct($DBFORUM_con)
{
$this->db = $DBFORUM_con;
}
public function addCount($id)
{
try
{
$stmt = $this->db->prepare("SELECT MAX(a_id) AS Maxa_id FROM forum_answer WHERE question_id = :id");
$stmt->execute(array(':id'=>$id));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0)
{
$Max_id = $userRow['Maxa_id'] + 1;
return $Max_id;
}
else {
$Max_id = 1;
return $Max_id;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
Then in my page that processes the form:
//require class
$id = $_POST['id'];
if ($forum->addCount($id))
{
echo $Max_id;
}
else
{
echo $Max_id;
}
You're not assigning the return value to anything.
Try
$id = $_POST['id'];
$Max_id = $forum->addCount($id)
if ($Max_id)
{
echo $Max_id;
}
else
{
echo $Max_id;
}
When I am fetching data from database in array it's showing only one element of each column. I am using below query:
$stmt = $conn_obj->select(' user ',' * ',' status = "updated" ', $order=NULL, $group=null, $fromRecordNum.','.$recordsPerPage);
and select function is below:
private function tableExists($table) {
//$this->con = $this->createconnection();
$query = 'SHOW TABLES FROM ' . $this->db . ' LIKE "'.trim($table).'"';
//echo ''.$query;
$tablesInDb = mysqli_query($this->con, $query);
if ($tablesInDb) {
if (mysqli_num_rows($tablesInDb) == 1) {
//echo ''.mysqli_num_rows($tablesInDb);
return true;
}
else {
return false;
}
}
}
public function select($table, $row = '*', $where= null,$order=null,$group=null, $limit=null, $join=null){
//$this->con = $this->createconnection();
//echo $join;
$q = 'select'.$row.' from '.$table;
//print_r($q);
if($join != null){
$q .= ' join '.$join;
}
if($where != null){
$q .= ' where '.$where;
print_r($q);
}
if($group != null){
$q .= 'group by'.$group;
//print_r($q);
}
if($order != null){
$q .= 'order by'.$order;
}
if($limit != null){
$q .= 'limit '.$limit;
print_r($q);
}
if ($this->tableExists($table)) {
$query = mysqli_query($this->con, $q) or die(mysql_error());
//print_r($query);
if ($query) {
$this->numResults = mysqli_num_rows($query);
//echo $this->numResults;
for ($i = 0; $i < $this->numResults; $i++) {
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for ($x = 0; $x < count($key); $x++) {
// Sanitizes keys so only alphavalues are allowed
if (!is_int($key[$x])) {
if (mysqli_num_rows($query) > 1)
$this->result[$i][$key[$x]] = $r[$key[$x]];
else if (mysqli_num_rows($query) < 1)
$this->result = null;
else
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
//print_r($this->result);
return $this->result;
} else {
return false;
}
} else{
return false;
}
}
I am fetching it with foreach loop as follow:
foreach($stmt as $row)
{
echo $row['user_Id'];
}
output is= 7 t : 2 2 2 u W u 2
and if I print whole array with print_r($row) then
output is= test ::1 2015-07-30 11:42:09am 2015-07-29 12:42:09pm 2015-07-30 12:28:57pm updated call_activated uninstall 2015-07-30 12:31:07pm.
If database has only one row with specified query then above problem is creating.
But in the case of two row with the specified query, its working fine as I want.
For multiple results, you are getting an array of arrays of elements.
For a single result, you are getting an array of elements.
So, for a single element, you have one foreach loop too many.
if in your example:
foreach($stmt as $row) {
echo $row['user_Id'];
}
Assuming $stmt contains the return value of your query:
foreach($stmt as $row) {
if (isset($row['user_Id'])) {
// do something with one single result record
} else {
foreach ($row AS $innerRow) {
// do something with each result record
}
}
}
The below query is only returning one result, even though there are multiple entries in the table with user_is 2. I m not sure what I m doing wrong.
function get_payments($user_id)
{
$sql = "SELECT txn_id, payer_email FROM orders WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
//echo $this->db->last_query();
if($query->num_rows() != 0) {
foreach($query->result() as $payment)
{
$data[] = $payment;
return $data;
}
}else{
return false;
}
}
This is what $this->db->last_query(); returns. SELECT txn_id, payer_email FROM orders WHERE user_id = '2'
Controller:
$profile_data['user_payments'] = $this->profile_model->get_payments($user_id);
View:
<?php
//var_dump($user_payments);
foreach($user_payments as $payment)
{
echo '<p>';
echo $payment->txn_id;
echo $payment->payer_email;
echo '</p>';
}
?>
try this:
<?php
function get_payments($user_id){
$this->db->select('txn_id, payer_email')
->from('orders')
->where('user_id', $user_id);
$qry = $this->db->get();
$res = $qry->result();
if($res){
return $res;
}else{
return false;
}
}
?>
there is a slight mistake here
foreach($query->result() as $payment)
{
$data[] = $payment;
return $data; // this line returns the data and it stops execution in first loop itself
}
it should be like
if($query->num_rows() != 0) {
foreach($query->result() as $payment)
{
$data[] = $payment;
}
return $data;
}
You should return $data from model after foreach loop completes.
if($query->num_rows() != 0) {
foreach($query->result() as $payment)
{
$data[] = $payment;
}
return $data;
}
else
{
return false;
}
Simple CI way:
...
$query = $this->db->query($sql, $user_id);
return $query->result_array();
No looping needed, nothing.
And I see you're using the object form, in that case do this:
return $query->result();
Then just loop it in your view like you're already doing.
So this is the whole model method:
function get_payments($user_id) {
$sql = "SELECT txn_id, payer_email FROM orders WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
return $query->result();
}
See the relevant docs here: http://ellislab.com/codeigniter/user-guide/database/results.html
And using Active Records (the most "natural" to CI):
function get_payments($user_id) {
return $this->db
->select('txn_id, payer_email')
->where('user_id', $user_id)
->get('orders')
->result();
}
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>