July 23, 2013

How to call a function of a class from other function file?

Mollo’s Question:

I know thats not the best title for my question but I coulnd’t come up with a better one (Suggestions are welcome)

Well, this is my situation, I have 3 files:

1) classDBConn.php – In this file is where I connect to the DB and have some functions like this:

class DBConn{
var $conexion;
private $querySql;
var $respuesta;
var $resultado;
function __construct() { 
    $this->conexion = @mysqli_connect('localhost', 'root', 'pass', 'dataBase');
    if(!$this->conexion){
        die('error de conexion('.mysqli_connect_errno().')'.mysqli_connect_error());    
    }
}
function checkBracketGanador($id_torneo){
    $this->querySql = "SELECT COUNT(id_ganador) FROM brackets WHERE id_torneo = '$id_torneo'";
    $this->respuesta = mysqli_query($this->conexion,$this->querySql);
    $this->resultado = mysqli_fetch_array($this->respuesta);
    return $this->resultado[0];
}
// More functions with queries

Note: queries and functions are fine

2)inc_conf.php – In this file is where I create the session and object DBConn. Code:

session_start();
include('classDBConn.php');
$functionsDBConn= new DBConn();
$id_usuario = isset($_SESSION["IDUSUARIO"]) ? $_SESSION["IDUSUARIO"] : false;

3) workingOn.php – In this file is where I make calls to DBConn in order to use those queries. If I do a call like this is just fine:

$res = $functionsDBConn->checkBracketGanador($id_torneo);
echo $res;

But, if I do it inside a function is where everything goes wrong

function test(){
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}
$a = test();
echo $a;

I keep getting this error:

Fatal error: Call to a member function checkBracketGanador() on a non-object in …/someFolder/workingOn.php on line 67

I’ve tried making public functions in classDBConn but didn’t work

What I’m doing is calling the function outside the function and sending the result as a parameter to the other function but thats exactly what I want to avoid

Any help is appreciate. Thanks in advance.

This is to do with scope.

I assume you instantiate $functionsDBConn = new DBConn(); outside the function at the same level as

$a = test();

If so you have 2 options

One:

function test(){
    global $functionsDBConn;
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}

$functionsDBConn = new DBConn();
$a = test();
echo $a;

Two:

function test(&$functionsDBConn){
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}
$functionsDBConn = new DBConn();
$a = test($functionsDBConn);
echo $a;

Basically you have to make the object you instantiated visible within the scope of your test() function by either telling the test() function it is available within the global scope global $functionsDBConn; or passing it into the function as a parameter.

You could also make checkBracketGanador() a static method but lets not get to complex all in a rush.

Use global keyword inside the function. The variable inside the function will not call values outside its scope.

function test(){
    global $functionsDBConn;
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}
March 10, 2013

Search code error

Question by IMEzzat

I have a php/ mysql search code like the following:

error_reporting(E_ALL);
ini_set('display_errors', '1');

$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
    $searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['searchquery']);

    if($_POST['filter'] == "user"){
        $sqlCommand = "SELECT id, username AS title FROM users 
          WHERE MATCH (username,email) AGAINST ('$searchquery')";
    } else if($_POST['filter'] == "email"){
        $sqlCommand = "SELECT id, blog_title AS title FROM blog 
          WHERE MATCH (blog_title,blog_body) AGAINST ('$searchquery')";
    }

    include_once("php_includes/db_conx.php");

    $query = mysql_query($sqlCommand) or die(mysql_error());

    $count = mysql_num_rows($query);
    if($count > 1){
        $search_output .= 
          "<hr />$count results for <strong>$searchquery</strong>
           <hr />$sqlCommand<hr />";

        while($row = mysql_fetch_array($query)){
            $id = $row["id"];
            $title = $row["title"];
            $search_output .= "Item ID: $id - $title<br />";
        } // close while
    } else {
        $search_output = 
          "<hr />0 results for <strong>$searchquery</strong>
           <hr   />$sqlCommand";
    }
}

When I run this code I got the following errors:

Warning: mysql_query() [function.mysql-query]: Access denied for user 'famebox'@'localhost' (using password: NO) in /home/famebox/public_html/search.php on line 15

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/famebox/public_html/search.php on line 15
Access denied for user 'famebox'@'localhost' (using password: NO)

Answer by Starx

Access denied for user ‘famebox’@’localhost’ (using password: NO)

Your database username and password and possibly the database name is incorrect. Check these details and verify them.

Above error message says you haven’t specified a password.

April 15, 2012

SQL Statement Giving me an error?

Question by PHPLOVER

My code below (must be something to do with sql statement (the UPDATE query statement), basically when i go in browser and visit script with a key that i know exists in the database i get the following error:

[15/04/2012 18:33:57] - exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'user_activation_key'' in C:wampwwwuser-verify.php:53
Stack trace:
#0 C:wampwwwuser-verify.php(53): PDOStatement->execute(Array)
#1 {main}

Here is my code:, not sure what it saying about duplicate entry, as the user_activation_key column is unique and yes i am using InnoDB and foreign keys for data interigty.

// check if key is set and alphanumeric and equals 40 chars long
// we use sha1 so it will always be 40 chars long.
if(isset($_GET['key']) && ctype_alnum($_GET['key']) && strlen($_GET['key']) == 40){
    $key = trim($_GET['key']);
}

// if key isset
if(isset($key)){

try {
        // connect to database
        $dbh = sql_con();

        // if key is of valid length and type we need to update the `user_activation_key` in the `users_status` table to NULL
        // and update the `user_status`in the `users` table to 1 (tinyint)(active) based on the condition that the 
        // activation key can be found in the users_status.user_activation_key column and user_uid match in both users_status and users table
        $stmt = $dbh->prepare("
                            UPDATE
                                users
                            JOIN
                                users_status
                            ON
                                users_status.user_activation_key = ?
                            SET
                                users.user_status = 1,
                                users_status.user_activation_key = NULL
                            WHERE
                                users_status.user_uid = users.user_uid");

        // execute query
        $stmt->execute(array($key));

        if ( $stmt->rowCount() > 0 ) {

            echo 'account now activated';
            exit;

        } else {
            echo 'could not activate account at this time';
            exit;
        }

    // close database connection
    $dbh = null;

} // if any errors found log them and display friendly message
catch (PDOException $e) {
    ExceptionErrorHandler($e);
    require_once($footer_inc);
    exit;
}

} else {

// else key not valid or set
echo '<h1>Invalid Activation Link</h1>';

$SiteErrorMessages =
"Oops! Your account could not be activated. Please recheck the link in your email.
The activation link appears to be invalid.<br /><br />
If the problem persists please request a new one <a href='/member/resend-activation-email'>here</a>.";

SiteErrorMessages();

include($footer_inc);
exit;

}

Not sure why i am getting that error, any know what it means exactly ?

It won’t perform the update even thou the key exists in the users_status table. if i enter an invalid key it says could not activate account at this time which is what it should do but when the key is valid it should update but it’s outputting the error above.

Thanks,
phplover

UPDATE:

Thanks for the quick replies as always!

Here is the the database design for those two tables.

CREATE TABLE `users` (
  `user_uid` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'users unique id',
  `user_status` tinyint(1) unsigned NOT NULL COMMENT '0 = verify | 1 = active |  2 =  suspended | 3 = delete | 4 = spam |',
  `user_login` varchar(15) NOT NULL COMMENT 'users login username',
  `user_pass` char(152) NOT NULL,
  `user_email` varchar(255) NOT NULL COMMENT 'users email',
  `user_registered` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'user registration date',
  `user_display_name` varchar(60) NOT NULL COMMENT 'users display name (first & last name)',
  `user_failed_logins` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT 'failed login attempts',
  PRIMARY KEY (`user_uid`),
  UNIQUE KEY `user_login` (`user_login`),
  UNIQUE KEY `user_email` (`user_email`),
  KEY `user_pass` (`user_pass`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT=Users Table';

CREATE TABLE `users_status` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'auto generated id',
  `user_uid` int(10) unsigned NOT NULL,
  `user_activation_key` char(40) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_uid` (`user_uid`),
  UNIQUE KEY `user_activation_key` (`user_activation_key`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='user status table, when a user registers they must first activate there account';


ALTER TABLE `users_status`
  ADD CONSTRAINT `FK_user_status` FOREIGN KEY (`user_uid`) REFERENCES `users` (`user_uid`) ON DELETE CASCADE ON UPDATE CASCADE;

Answer by Starx

On your query you are setting users_status.user_activation_key as NULL, and I am pretty sure, it has a UNIQUE index and value NULL must be already available in the table.

That’s why you are receiving that error.

April 11, 2012

mysql database insert is changing all IDs to 4294967295

Question by three3

Something really weird is going on with my database. I am using PHP to insert data into my database and I have been doing this for the past 2 years without any problems. When a customer makes a payment on my website, I store all of the data from that transaction in my database. Each transaction has a unique “transaction_id”. When I insert the payment information into the database, all of the information is correctly inserted except for the “transaction_id”. ALL transactions are given the “transaction_id” of “4294967295”. So I did some testing. Here is what I did:

1) I echoed out the “transaction_id” to my screen to see what is would say. The results were that the “transaction_id” that was being echoed out was CORRECT. It was not the repeating “4294967295”. However, when I look in my database, it shows “4294967295”.

2) This time I decided to echo out the query to my web browser. The query was CORRECT. In the query, the CORRECT “transaction_id” was in the query. However, when I look in my database, it shows “4294967295”.

I have 3 different pages where customers can make payments. ALL 3 pages started doing this on April 6th, 2012. None of those pages were modified at all. I have not modified those pages in over 2 years. Any help is greatly appreciated!

$query = "INSERT INTO payments (customer_id, transaction_id, invoice_number, authorization_code, subscription, subscription_id, avs_result, cvv_result, amount, full_tuition, payment_date, ip_address) VALUES ({$_SESSION['customer_id']}, {$_SESSION['transaction_id']}, {$_SESSION['invoice_number']}, '{$_SESSION['authorization_code']}', '{$_SESSION['subscription']}', {$_SESSION['subscription_id']}, '{$_SESSION['avs_result']}', '{$_SESSION['cvv_result']}', {$_SESSION['amount']}, {$_SESSION['full_tuition']}, '{$_SESSION['payment_date']}', '{$_SESSION['ip_address']}')" ;
$result = mysqli_query($dbc, $query) OR die ('<p>There was an error with the INSERT payments query.: ' . mysqli_error($dbc) . '<br />Query:' . $query . '</p>') ;

echo '<p>Transaction ' .  $_SESSION['transaction_id'] . ' has been <font color="green">APPROVED</font> by the system.</p>' ;

echo '<br /><br />' ;

echo '<p>Below is a summary:</p>' ;
echo '<p>Transaction ID: ' .  $_SESSION['transaction_id'] . '<br />
Payment Method: XXXX<br />
Amount: $' . $amount . '<br />
Customer Name: ' . $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '<br />
</p>' ;

echo "<p>Note: Please do NOT click the browser's Back button to enter a new transaction.</p>" ;


echo $query ;

Answer by user282172

Your number is larger than the field in the DB can handle…

4294967295 is the largers number 32 bits can hold, your transaction ID is now larger than the numerical field your DB can hold.

Answer by Starx

Change the data type of the transaction_id to BIGINT

April 2, 2012

Show multiple rows in MySQL

Question by ramesh

I had a table like this

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
1    |   SAM1
3    |   SAM3
7    |   SAM7
6    |   SAM6

I need to show the results using this query

SELECT name,id FROM tblnameWHERE id IN (1,2,7,6,1)

and getting the following result

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
7    |   SAM7
6    |   SAM6

My problem is this skipped last id , ie 1 . I need something like this

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
7    |   SAM7
6    |   SAM6
1    |   SAM1

With out using the loop query ( like follows ) any other method for doing this ?

$ids=array(1,2,7,6,1);
$i=0;
foreach($ids as $id){

$sql=mysql_query("SELECT * FROM tblname WHERE id=$id");
// Store value to array 

}

Please help

Answer by ShinTakezou

The query

SELECT name,id FROM tblname WHERE id IN (1,2,7,6);

should show duplicate rows; e.g. if there are really in the table two distinct rows with the very same id, then the query will show them (since there’s no DISTINCT keyword).

Instead, if you want to create duplicate lines starting from a table containing single lines, you have to join your table with a table having repeated 1 (in your case); another way could be to use union like this:

SELECT  name, id FROM tblname WHERE id IN (1,2,7,6)
  UNION ALL
SELECT name, id FROM tblname WHERE id = 1;

Edit

Since your id is a primary key, it will be unique, hence the “problem” you’re experiencing. If you want to allow duplicate rows on insert, remove the primary key. If you need it, consider the possible solutions suggested above.

Answer by Starx

What you are attempting is wrong.

Both the fields have same id and same value as well. You said id is your primary key on your table.

A primary key cannot be duplicated among the rows. That is the whole point of having a primary key

You mustn’t have declared the id field as primary key.

  • Remove the bottom row
  • Add primary key to the field , run this query

    ALTER TABLE `tablename` ADD PRIMARY KEY(id) AUTO_INCREMENT
    

Now from this point ahead, you will have unique id for all the records you have and you will have no problem on selecting the rows.

December 29, 2011

mysqli_affected_rows, mysql subtract 2 columns error

Question by Max

I have a column I want to update with results of the difference between 2 mysql columns and count how many rows were affected. In my case it can only be 1. This is the mysql query I am using which is not consistent at all

$connection->query("UPDATE items SET Quantity_Available = Quantity - Quantity_Committed WHERE Item_ID = '$itemid'");
if($count=$connection->affected_rows!=1){echo $count;die('makassi');}

If I replace the Quantity_Committed with a numeric value, I get what I want i.e the code continues. However if I leave it as it is, I get the proper $count figure(1) but it also fails by echoing ‘makassi’ which it shouldn’t.

Is this an improper way of subtracting 2 mysql columns or is this a bug in the php mysqli api??
This is really baffling to me!! Help please

Answer by Starx

This is a bad practice what you are trying to do. If a column in the database is derived from another column already in the column. Then such is create redundancy is the database. All a database should be normalized as much as possible. Please read here about data normalization.

Whatever you are trying to do can be achieved in a much better way. Like

Filtering the records

SELECT * FROM items WHERE Quantity - Quantity_Column > 5

Or, retrieving the quantity available.

SELECT (Quantify - Quantity_Column) as `Quality_Available` from items
March 18, 2011

Changing database records to xml file using php

Question by user643160

I am trying to pass items from a mysql database into an xml file using php. I have the php code that creates the xml file. But the values that are passed to it aren’t the ones from the mysql database. The database has 13 cols with 62 rows. I have five items in my foreach statement and when they displays on the web screen the values are output as follows:

Number of properties found : 62

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 R R R R R E E E E E W W W W W A A A A A h h h h h 1 1 1 1 1 < < < < < 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1

There are 65 items in the line above which is the 5 items in my foreach statement times the 13 cols in my database. This I think has something to do with it.

The following is my code:

<?php

@$db = new mysqli('localhost', 'root', '', 'siamsatire');

if (mysqli_connect_errno()) {
    echo 'error connecting to db';
    exit;
}
$query = "SELECT * from events";
$result = $db->query($query);
$num_results = $result->num_rows;
echo 'Number of properties found : <strong>' . $num_results . '</strong><br><br>';

for ($i=0; $i < $num_results; $i++) { 

    $row = $result->fetch_object(); 

    $name = $row->name; 
    $subtitle = $row->sub_title; 
    $date = $row->display_date; 
    $description = $row->slug; 
    $photo= $row->photo; 
    $thumb= $row->thumb; 

    /*echo '<tr>';
    echo "<td>$name</td>";
    echo "<td>$subtitle</td>";
    echo "<td>$date</td>";
    echo "<td>$description</td>";
    echo "<td>$photo</td>";
    echo "<td>$thumb</td>";1+0
    echo '<tr>';*/

} 

$doc = new DOMDocument("1.0");
$doc->formatOutput = true;

$r = $doc->createElement("events");
$doc->appendChild( $r );

foreach($row as $fieldvalue)
{
    $b = $doc->createElement( "event" );

    $name1 = $doc->createElement( "title" );
    $name1->appendChild( $doc->createTextNode( $fieldvalue['title'] ));
    $b->appendChild( $name1 );

    $subtitle1 = $doc->createElement( "subtitle" );
    $subtitle1->appendChild($doc->createTextNode( $fieldvalue['subtitle'] ));
    $b->appendChild( $subtitle1 );

    $date1 = $doc->createElement( "display_date" );
    $date1->appendChild($doc->createTextNode( $fieldvalue['display_date'] ));
    $b->appendChild( $date1 );

    $description1 = $doc->createElement( "slug" );
    $description1->appendChild( $doc->createTextNode( $fieldvalue['slug'] ));
    $b->appendChild( $description1 );

    $photo1 = $doc->createElement( "photo" );
    $photo1->appendChild( $doc->createTextNode( $fieldvalue['photo'] ) );
    $b->appendChild( $photo1 );

    $thumb1 = $doc->createElement( "thumb" );
    $thumb1->appendChild( $doc->createTextNode( $fieldvalue['thumb'] ) );
    $b->appendChild( $thumb1 );

    $r->appendChild( $b );
}

echo $doc->saveXML();
$doc->save("write.xml");

$result->free();
$db->close();
?>

Does anyone have any ideas as to what I’m doing wrong?

UPDATE


@starx – I changed my code around to look like this according to your code and this is what it looks like now.

<?php

    @$db = new mysqli( 'localhost', 'root', '', 'siamsatire');

    if (mysqli_connect_errno()) {
    echo 'error connecting to db';
    exit;
    }

    $query = "SELECT * from events";

    $result = mysql_query($query);  

    if(mysql_num_rows($result)) {
    $doc = new DOMDocument("1.0");
    $doc->formatOutput = true;

    while($row = mysql_fetch_assoc($result)) {
        $r = $doc->createElement( "events" );
        foreach($row as $field=>$value) {
            $tChild = $doc->createElement( $field );
            $tChild->appendChild( $doc->createTextNode($value) );
            $r->appendChild( $tChild );     
        }
        $doc->appendChild($r);
    }
        $doc->appendChild( $r );
        echo $doc->saveXML();
        $doc->save("write.xml");
    }

    //$result->free();
        //$db->close();
    ?>

And these are the errors I got with it.’

Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:xampphtdocssiamsatire1.php on line 12

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:xampphtdocssiamsatire1.php on line 12

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:xampphtdocssiamsatire1.php on line 14'

Do you know why I got them?

I then changed mysql_query to mysqli_query which cut the errors down to:

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:xampphtdocssiamsatire1.php on line 12

Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:xampphtdocssiamsatire1.php on line 14

Answer by Starx

Here is a better and correct solution

$query = "SELECT * from events";
$result = mysql_query($query);
if(mysql_num_rows($result)) {
    $doc = new DOMDocument("1.0");
    $doc->formatOutput = true;

    while($row = mysql_fetch_assoc($result)) {
        $r = $doc->createElement( "events" );
        foreach($row as $field=>$value) {
            $tChild = $doc->createElement( $field );
            $tChild->appendChild( $doc->createTextNode($value) );
            $r->appendChild( $tChild );     
        }
        $doc->appendChild($r);
    }
    $doc->appendChild( $r );
    echo $doc->saveXML();
    $doc->save("write.xml");
}

You can integrate above code with your library if you want.

UPDATE (after question Update)


Here is your working solution using mysqli

<?
@$db = new mysqli( 'localhost', 'root', '', 'siamsatire');
if (mysqli_connect_errno()) {
    echo 'error connecting to db';
    exit;
}
$query = "SELECT * from events";
$result = mysqli_query($db,$query);  
if(mysqli_num_rows($result)) {
    $doc = new DOMDocument("1.0");
    $doc->formatOutput = true;

        while($row = mysqli_fetch_assoc($result)) {
            $r = $doc->createElement( "events" );
            foreach($row as $field=>$value) {
                $tChild = $doc->createElement( $field );
                $tChild->appendChild( $doc->createTextNode($value) );
                $r->appendChild( $tChild );     
            }
            $doc->appendChild($r);
        }
        $doc->appendChild( $r );
        echo $doc->saveXML();
        $doc->save("write.xml");
}

//$result->free();
//$db->close();
?>
May 17, 2010

output all data from db to a php page

Question by Sarit

I’m a real beginner with PHP & mysql.
Just for studying and for a simple example at school I would like to work this simple query and possibly output all the rows (or maybe even one) to a very basic output on a php page:

<?php
$user= "root";
$host="localhost";
$password="";
$database = "PetCatalog";
$cxn = mysqli_connect($host,$user,$password,$database)
or die ("couldn’t connect to server");
$query = "SELECT * FROM Pet";
$result = mysql_query($cxn,$query) or die ("Couldn’t execute query.");
$row = mysqli_fetch_assoc($result);
echo "$result";
?>

this is the error message i’ve been getting:

Warning: mysql_query() expects parameter 1 to be string, object given in C:xampplitehtdocsmyblogquery.php on line 18
Couldn’t execute query.

What should I do?
Thanks!

Answer by Starx

<?php
$user= "root";
$host="localhost";
$password="";
$database = "PetCatalog";
$cxn = mysqli_connect($host,$user,$password,$database)
or die ("couldn’t connect to server");
$query = "SELECT * FROM Pet";
$result = mysql_query($query) or die ("Couldn’t execute query.");
while($row = mysqli_fetch_array($result)) {
          print_r($row);
}
?>

This should solve your problem

...

Please fill the form - I will response as fast as I can!