Solved

trouble with PHP/sql syntax

Posted on 2011-09-08
13
195 Views
Last Modified: 2012-05-12
In PHP, I"m trying to use a query something like this:

$query = mssql_query("SELECT     CUSTOMER
FROM         SSCUSTOM
WHERE     (CUSTOMER LIKE '%$customer%')
 ");

I've tried various combinations of punctuation to properly offset the $customer variable, but nothing has worked.  Can someone help?

thanks.
0
Comment
Question by:kennmurrah
  • 5
  • 3
  • 2
  • +2
13 Comments
 
LVL 2

Expert Comment

by:shdwmage
Comment Utility
Try this
$query = 'SELECT customer FROM sscustomer WHERE (Customer like %' . $customer . '%)';

$result = @mdsql_query($query);

Open in new window

0
 
LVL 2

Expert Comment

by:shdwmage
Comment Utility
err MSsql not Mdsql fat fingers sorry.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
This is the format that I'm using on a working example.  I'm assuming that your field and table names are the correct case.  Depends on whether you have set up your database to be case sensitive or not.
$query = mssql_query("SELECT CUSTOMER FROM SSCUSTOM WHERE CUSTOMER LIKE '%$customer%'");

Open in new window

0
 
LVL 27

Accepted Solution

by:
Lukasz Chmielewski earned 500 total points
Comment Utility
Or if Dave's won't work, try this:


$query = mssql_query("SELECT CUSTOMER FROM SSCUSTOM WHERE CUSTOMER LIKE '%".$customer."%'");

Open in new window

0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
... of course I'm sure Dave is right :P
0
 

Author Comment

by:kennmurrah
Comment Utility
I just noticed that I'm getting the error: "Warning: mysql_fetch_array(): supplied resource is not a valid MySQL result resource in /var/www/psilookup/2.php on line 11" ....

<?php
$connect = mssql_connect("psi", "php", "holistic") or die ("couldn't
connect");

mssql_select_db('[PS11_0_2]', $connect);

$query = mssql_query("SELECT CUSTOMER FROM SSCUSTOM WHERE CUSTOMER LIKE '%".$customer."%'");

	 if ($row = mysql_fetch_array($query)) { 
do { 
	$customer = $row["CUSTOMER"];
	$url_customer = urlencode($customer);
	
 echo "<a href=\"3.php?customer=$url_customer\">" . $customer . "</a><br>";
// echo "<a href=\"3.php?customer=$url_customer\">" . $customer .  "</a><br>";
}
 while($row = mysql_fetch_array($result)); } else {print "<p> No matches found.";} 
 
 ?>

Open in new window


so I'm really confused now.

0
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 2

Expert Comment

by:shdwmage
Comment Utility
I believe it has to do with your if statement.  you aren't performing the query and saving it anywhere.
0
 
LVL 2

Expert Comment

by:shdwmage
Comment Utility
Nevermind, i read it wrong.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
!! You can't mix MySQL and MS SQL, they are two different databases and drivers.
0
 
LVL 2

Expert Comment

by:shdwmage
Comment Utility
I am not sure if this makes a difference or not:

You have MSSQL in one location and MYSQL in the other.

<?php
$connect = mssql_connect("psi", "php", "holistic") or die ("couldn't connect");

mssql_select_db('[PS11_0_2]', $connect);

$query = mssql_query("SELECT CUSTOMER FROM SSCUSTOM WHERE CUSTOMER LIKE '%".$customer."%'");

if ($row = mssql_fetch_array($query)) { 
	do { 
		$customer = $row["CUSTOMER"];
		$url_customer = urlencode($customer);
		echo "<a href=\"3.php?customer=$url_customer\">" . $customer . "</a><br>";
		// echo "<a href=\"3.php?customer=$url_customer\">" . $customer .  "</a><br>";
		}
		while($row = mysql_fetch_array($result)); 
	} 
	else {
		print "<p> No matches found.";
		} 

?>

Open in new window

0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
Here's the correction but that code does not look complete.
<?php
$connect = mssql_connect("psi", "php", "holistic") or die ("couldn't
connect");

mssql_select_db('[PS11_0_2]', $connect);

$query = mssql_query("SELECT CUSTOMER FROM SSCUSTOM WHERE CUSTOMER LIKE '%".$customer."%'");

         if ($row = mysql_fetch_array($query)) { 
do { 
        $customer = $row["CUSTOMER"];
        $url_customer = urlencode($customer);
        
 echo "<a href=\"3.php?customer=$url_customer\">" . $customer . "</a><br>";
// echo "<a href=\"3.php?customer=$url_customer\">" . $customer .  "</a><br>";
}
 while($row = mssql_fetch_array($result)); } else {print "<p> No matches found.";} 
 
 ?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Warning: mysql_fetch_array(): supplied resource is not a valid MySQL result ...

This almost always means the query failed.  MySQL is not a black box.  It can and will fail, sometimes for reasons that are outside of your control, and your programming needs to test for success whenever you make a call to MySQL.  When a query fails you will want to know why.

To understand why, you need to see the contents of mysql_error().  Here is a little code snippet with some teaching examples for a few of the basics in PHP + MySQL.  As you can see, it will help you visualize the query string and any errors that might occur.

If you want a good learning resource on the subject, this book is very readable and has excellent examples.
http://www.sitepoint.com/books/phpmysql4/

HTH, ~Ray
<?php // RAY_mysql_example.php
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



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


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

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




// ESCAPE AN EXTERNAL DATA FIELD FOR 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, SHOW THE ERROR
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// 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);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/>$sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $num ROWS OF DATA ";
    echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
while ($row = mysql_fetch_assoc($res))
{
    var_dump($row);
}




// A 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)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// 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)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// 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 108

Expert Comment

by:Ray Paseur
Comment Utility
Interesting.  The answer accepted from Roads_Roads produces EXACTLY the same query string as the answer that was offered up by DaveBaldwin earlier.  Here is the code that proves it.  It is usually a good idea to test the code posted here at EE before you assume that something is right or wrong.

However the most important part about this question is understanding how to visualize errors.  In order to do that you would never create the query string in the same statement as the function call.  You would create the query string separately in its own variable, so you can print it out in case you get an error.
<?php // RAY_temp_kennmurrah.php
error_reporting(E_ALL);

$db = "SELECT CUSTOMER FROM SSCUSTOM WHERE CUSTOMER LIKE '%$customer%'";
$rr = "SELECT CUSTOMER FROM SSCUSTOM WHERE CUSTOMER LIKE '%".$customer."%'";

echo $db;
echo "<br/>";
echo $rr;

Open in new window

0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
PHP and Soap 3 26
Select2 jquery help 9 41
SQL JOIN 6 27
Is it necessary to have authentication controls on function pages? 4 17
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
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…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to shrink a transaction log file down to a reasonable size.

763 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

13 Experts available now in Live!

Get 1:1 Help Now