开发者

PHP/MySQL - appending strings together to make a query..?

开发者 https://www.devze.com 2023-03-10 01:51 出处:网络
Is there any reason why this shouldn\'t work? $events_query = \"SELECT eventID, event_name, event_type, event_开发者_JAVA技巧address, event_duration, event_date, event_time, event_description, num_a

Is there any reason why this shouldn't work?

$events_query = "SELECT eventID, event_name, event_type, event_开发者_JAVA技巧address, event_duration, event_date, event_time, event_description, num_attending
                             FROM events WHERE event_city = '$city' " .$type_query .$date_query .$time_query;  
$events_list = mysql_query($events_query); 

/* Where $type_query and $date_query are things like:

$type_query = "AND event_type = '$type' "; 

*/ 

Basically the above code is not giving me the expected results, so I'm wondering if there's a problem with the way I'm doing it in PHP. If not then it means I have a logic problem, which I would prefer, because I really don't know how else to do these variable-type queries that I want to do. Basically my queries will vary by the user-inputted data.

Thanks.


Try putting in an

echo $events_query;

statement in your code to see what the generated SQL is. It's much easier to see any errors that way. Generally speaking, though, yes, that's perfectly legal and generating SQL like that is quite common.


There's nothing inherently wrong with that method of constructing a query. You would have to explain how the results differ from your expectation, and I would suggest echoing/logging the final $events_query and comparing that with your needs..


String concatenation is a legitimate way to build an SQL query, and so long as you obey PHP's syntax requirements you can generate valid SQL this way.

Print out the generated string (to a log file, or to the web page) and check that it matches what you thought you were generating. It might have a stray quotation mark or semi-colon which will alter or prematurely terminate the query.

Paste that string into MySQL's console and see if it gives any additional errors.

The usual warnings about accepting user input directly into an SQL query apply.


 $events_query = "SELECT eventID, event_name, event_type, event_address, event_duration, event_date, event_time, event_description, num_attending FROM events WHERE event_city ='$city' $type_query $date_query $time_query ";

echo this query copy run in phpmyadmin we get the results, we can modify query then.

0

精彩评论

暂无评论...
验证码 换一张
取 消