Solved

Why will this query not print?

Posted on 2013-01-05
8
202 Views
Last Modified: 2013-01-21
Here's the query:

$data=SqlQuery("","
SELECT *
FROM cart_products
WHERE featured='1'
");

I want to see what the page is seeing, so I do: echo $data and nothing shows up. What am I missing?
0
Comment
Question by:brucegust
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 250 total points
ID: 38747564
What is SqlQuery? Or better: which type of function is it? Are you using some framework? I ask because in the old, plain php you should write something like

$query = "SELECT * FROM cart_products WHERE featured='1'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); 
print_r($row);

Open in new window


Your syntax is quite different but this could depend on the fact you are using some framework or some other script which uses its own function to get data from a database.
0
 

Author Comment

by:brucegust
ID: 38747626
This is someone else's code and I'm trying to debug a problem that surfaced a few days ago.

Your question prompted my going back and looking at things a bit closer. Here's the function:

function SqlQuery($database,$sql){

            if (strpos($_SERVER['SERVER_NAME'],"snowdogweb")){
            $user="";
            $pass="";
            $datasource="";
            $server="";
            }else{
            $user = "";
            $pass="";
            $datasource = "";
            $server="";
            }

            $dbase_user = mysql_connect($server,$user,$pass);
            mysql_select_db($datasource, $dbase_user);
            
            $query_results = mysql_query($sql, $dbase_user);
                                    
            
            return $query_results;

}

The problem is, I'm getting an error in that while there's data to retrieve, the array is empty. So I'm trying to see how the query is being read, but I don't know how to get it to print given the way it's been coded.

Thoughts?
0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 38747645
The script posted here almost certainly has been redacted or otherwise changed.  An if() statement that creates four identical variables no matter which test is passed makes no sense at all.  You might want to add some error reporting capabilities to these scripts.  Add error_reporting(E_ALL); to the top of the scripts.  Use the design patterns shown here to allow visualization of any notices, warnings and errors.

<?php // RAY_mysql_example.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);


// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQL
// MAN PAGE: http://php.net/manual/en/ref.mysql.php
// MAN PAGE: http://php.net/manual/en/mysql.installation.php
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
// MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
// MAN PAGE: http://php.net/manual/en/function.mysql-query.php
// MAN PAGE: http://php.net/manual/en/function.mysql-errno.php
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php
// MAN PAGE: http://php.net/manual/en/function.mysql-num-rows.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-array.php
// MAN PAGE: http://php.net/manual/en/function.mysql-insert-id.php
// MAN PAGE: http://php.net/manual/en/function.error-log.php


// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";


// OPEN A CONNECTION TO THE DATA BASE SERVER
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $err <br/>";
}

// SELECT THE MYSQL DATA BASE
if (!mysql_select_db($db_name, $db_connection))
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $err <br/>";
    die('NO DATA BASE');
}
// IF THE SCRIPT GETS THIS FAR IT CAN DO QUERIES


// ESCAPE ALL DATA FIELDS BEFORE USE IN MYSQL QUERIES
$safe_username = mysql_real_escape_string($_POST["username"]);


// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . mysql_errno()
    . ' ERROR: '
    . mysql_error()
    ;
    error_log($err);

    // HANDLE THE PROGRAMMATIC CONSEQUENCES HERE
    die($err);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS


// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = mysql_num_rows($res);
$fmt = number_format($num);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/> $sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $fmt ROWS OF DATA ";
    echo "<br/> $sql <br/>";
}


// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
while ($row = mysql_fetch_assoc($res))
{
    // ROW BY ROW PROCESSING IS DONE HERE
    var_dump($row);
}


// ANOTHER WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($err);
}
// GET THE RESULTS SET ROW IN AN ARRAY WITH A NUMERIC INDEX - POSITION ZERO IS THE COUNT
$row = mysql_fetch_array($res, MYSQL_NUM);
$num = $row[0];
$fmt = number_format($num);
echo "<br/>THERE ARE $fmt ROWS IN THE TABLE";


// MAKING AN INSERT QUERY AND TESTING THE RESULTS
$sql = "INSERT INTO my_table (username) VALUES ('$safe_username')";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/> $sql <br/>";
    die($err);
}


// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
$id  = mysql_insert_id($db_connection);
echo "<br/>YOU JUST INSERTED A RECORD WITH AUTO_INCREMENT ID = $id";

Open in new window

0
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 31

Expert Comment

by:Marco Gasi
ID: 38747652
You can simply put a beautyful

echo $sql;

as first line of your function in order to see if the query is correctly passed. I presume that all values left blank are so for privacy reasons: I mean that in this function

$data=SqlQuery("","
SELECT *
FROM cart_products
WHERE featured='1'
");

if you don't pass a database name it won't work, but I think you left it blank only here at EE

Cheers
0
 

Author Comment

by:brucegust
ID: 38747811
Here's what I did:

$data=SqlQuery("","
SELECT *
FROM cart_products
WHERE featured='1'
");
echo $sql;

on the page I get an error that says Undefined variable: sql in /mnt/vhosts/heavydutylighting.com/httpdocs/index.php on line 103.

What do you think?
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38747829
The script appears to assign a value to a variable named $data, but not to a variable named $sql.  I think you might want to get some assistance from a professional programmer.  It will save you a lot of time.  You can learn about how to use var_dump() to print out the values of variables after they are assigned (variable name appears to the left of the single equal sign).  For example, in the most recent example we saw this:
$data=SqlQuery("","
SELECT *
FROM cart_products
WHERE featured='1'
");
echo $sql;

Open in new window

and a more useful code segment might be this:
$data=SqlQuery("","
SELECT *
FROM cart_products
WHERE featured='1'
");
var_dump($data);

Open in new window

0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 38748158
To see if the variable $sql is passed correctly you have to do this:

your main script
$data=SqlQuery("","
SELECT *
FROM cart_products
WHERE featured='1'
");

Open in new window


within the function
function SqlQuery($database,$sql){

            echo $sql;            

            if (strpos($_SERVER['SERVER_NAME'],"snowdogweb")){
            $user="";
            $pass="";
            $datasource="";
            $server="";
            }else{
            $user = "";
            $pass="";
            $datasource = "";
            $server="";
            }

            $dbase_user = mysql_connect($server,$user,$pass);
            mysql_select_db($datasource, $dbase_user);
            
            $query_results = mysql_query($sql, $dbase_user);
                                    
            
            return $query_results;

}

Open in new window


This way you'll see if the function SqlQuery reads correctly the $sql variable. I repeat: are all varibles in the function lewft empty for privacy resons ($user, $pass, $datasource, $server? And why the function expects a $database variable if it doesn't use it to fill $datasource variable? Or $database variiable is superflous or it is superflous $datasource variable.
0
 
LVL 10

Expert Comment

by:d4durvesh
ID: 38759134
First of have you create database
 and
 created table in it?
 Have you connected database correctly?
If so has there is featured column in your cart_product table?
What you are exactly echoing? $sql or $data?
Pls check n Let us know!
Thank you!
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Blocking submission of a web-based form 6 20
Insert won't work due to space in column name 5 21
Fulfillment API php code sample 1 40
Php recording post 4 39
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question