Solved

Why will this query not print?

Posted on 2013-01-05
8
201 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 30

Accepted Solution

by:
Marco Gasi earned 250 total points
Comment Utility
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
Comment Utility
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 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
Comment Utility
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
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:brucegust
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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 30

Expert Comment

by:Marco Gasi
Comment Utility
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
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

728 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now