deko Posted October 5, 2009 Share Posted October 5, 2009 Here's the code in question: <?php $var = trim($_GET['var']); $cnx = mysql_connect('localhost','user','paswd'); $db = mysql_select_db('database_1'); if ($cnx && $db) { $sql = "SELECT something where var = ".$var;"; $result = mysql_query($sql); while ($foo = mysql_fetch_array($result)) { [do stuff with data] } // now get stuff from database_2 if (@mysql_select_db('database_2')) { $sql = "SELECT something else based on $var_id;" $result = mysql_query($sql); while ($bar = mysql_fetch_array($result)) { [do stuff with data] } } Two questions: 1) How do I test $result (or mysql_fetch_array($result)) before I get into the while loop? 2) Is it okay to switch databases like this? I assume I DON'T need to mysql_close; here... just mysql_select_db to use another database--is this correct? thanks. EDIT: please make use of tags Link to comment https://forums.phpfreaks.com/topic/176522-solved-how-to-test-if-query-returned-anything/ Share on other sites More sharing options...
elabuwa Posted October 5, 2009 Share Posted October 5, 2009 Hey, I'm kind of a noob too. but one thing i noticed is that you dont count the number of results that match your search criteria. 1. for eg your code may be as follows. $sql = "SELECT something FROM TABLENAME where var = ".$var;"; $result = mysql_query($sql); $num=mysql_num_rows($result); echo $num; \\*1 while($row = mysql_fetch_array($result)) { echo $row['something']; \\*2 } at *1 : it will display the number of records that matched with your search criteria. at *2 : it will display the field value which matches with your search criteria. This will happen until php loops through all the matched records. hope this helps. 2. Im sorry I dont know much bout switchin database. I always use one database for one project. Link to comment https://forums.phpfreaks.com/topic/176522-solved-how-to-test-if-query-returned-anything/#findComment-930524 Share on other sites More sharing options...
Mchl Posted October 5, 2009 Share Posted October 5, 2009 1. As elabuwa said, use mysql_num_rows to check number of rows returned. 2. Yup. It's fine. Link to comment https://forums.phpfreaks.com/topic/176522-solved-how-to-test-if-query-returned-anything/#findComment-930536 Share on other sites More sharing options...
deko Posted October 6, 2009 Author Share Posted October 6, 2009 Thanks Mchl and elabuwa -- mysql_num_rows is the answer! Exactly what I needed... Link to comment https://forums.phpfreaks.com/topic/176522-solved-how-to-test-if-query-returned-anything/#findComment-931194 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.