PHP - How Would I Run The Following Mysql Query In A Php Script ?
TRUNCATE TABLE CubeCart_cats_idx;
INSERT INTO CubeCart_cats_idx (productid, cat_id) SELECT productid, cat_id FROM CubeCart_inventory; I an running the following in MyPHPAdmin, but need this to be automated in a PHP script, how would I do it ? all help is appreciated, still new to PHP & MySQL many thanks D Similar TutorialsHere is my code: // Start MySQL Query for Records $query = "SELECT codes_update_no_join_1b" . "SET orig_code_1 = new_code_1, orig_code_2 = new_code_2" . "WHERE concat(orig_code_1, orig_code_2) = concat(old_code_1, old_code_2)"; $results = mysql_query($query) or die(mysql_error()); // End MySQL Query for Records This query runs perfectly fine when run direct as SQL in phpMyAdmin, but throws this error when running in my script??? Why is this??? Code: [Select] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= new_code_1, orig_code_2 = new_code_2WHERE concat(orig_code_1, orig_c' at line 1 I have a really weird problem. I'm trying to run a mysql query that works fine in phpmyadmin but in php script is giving me an error. The query is: Code: [Select] (SELECT DISTINCT art.`TEMPLATE`,gal.`ARTICLE_ID`,art.`TITLE`,art.`DESCRIPTION`,MATCH(art.`TITLE`,art.`DESCRIPTION`,gal.`CONTENT`) AGAINST ('WORD*' IN BOOLEAN MODE) AS score FROM articles art,galeries gal WHERE gal.`ARTICLE_ID`=art.`ARTICLE_ID` AND MATCH(art.`TITLE`,art.`DESCRIPTION`,gal.`CONTENT`) AGAINST ('WORD* ' IN BOOLEAN MODE)) UNION (SELECT DISTINCT `TEMPLATE`,`ARTICLE_ID`,`TITLE`,`DESCRIPTION`,MATCH(`TITLE`,`DESCRIPTION`,`CONTENT`) AGAINST ('WORD* ' IN BOOLEAN MODE) AS score FROM articles WHERE (MATCH(`TITLE`,`DESCRIPTION`,`CONTENT`) AGAINST ('WORD* ' IN BOOLEAN MODE))) ORDER BY score DESC LIMIT 0,30 Snipset from php script code: function search($start_row,$ammount,$search_key,$pages){ $start_row = intval($start_row) * $ammount; $return_val = ""; $symbols = array('/','\\','\'','"',',','.','<','>','?',';',':','[',']','{','}','|','=','+','-','_',')','(','*','&','^','%','$','#','@','!','~','`' );//this will remove punctuation $pattern = "#[^(\w|α|β|γ|δ|ε|ζ|η|θ|ι|κ|λ|μ|ν|ξ|ο|π|ρ|σ|τ|υ|φ|χ|ψ|ω|Α|Β|Γ|Δ|Ε|Ζ|Η|Θ|Ι|Κ|Λ|Μ|Ν|Ξ|Ο|Π|Ρ|Σ|Τ|Υ|Φ|Χ|Ψ|Ω|ς|ά|έ|ό|ί|ύ|ώ|ή|ϊ|ϋ|ΐ|ΰ|Ά|Έ|Ό|Ί|Ύ|Ώ|Ή|Ϊ|Ϋ|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#"; $search_key = greek_text::to_upper($search_key); $wc = strip_tags($search_key); $wc = preg_replace($pattern, " ", $wc); for ($i = 0; $i < sizeof($symbols); $i++) { $wc = str_replace($symbols[$i],' ',$wc); } $wc = str_replace("΄", " ", $wc); $wc = str_replace(chr(162), " ", $wc); if( !$keep_numbers ) { $wc = preg_replace('#(^|\s+)[\d\s]+(\s+|$)#',' ',$wc); $pattern = '#(^|\s+)([0-9]+[a-zA-ZαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩςάέόίύώήϊϋΐΰΆΈΌΊΎΏΉΪΫ]+\s*)+(\s+|$)#'; preg_match($pattern,$wc,$aa); $wc = preg_replace($pattern, " ", $wc); } $wc = trim(preg_replace("/\s\s+/", " ", $wc)); $wc = explode(" ", $wc); $cleaned_keyword = array_filter($wc); $cleaned_keyword = greek_text::removeStopWordsFromArray($cleaned_keyword); $stemmed_keywords = greek_text::stemWordsArray($cleaned_keyword); $query = "(SELECT DISTINCT art.`TEMPLATE`,gal.`ARTICLE_ID`,art.`TITLE`,art.`DESCRIPTION`,MATCH(art.`TITLE`,art.`DESCRIPTION`,gal.`CONTENT`) AGAINST ('"; while(list($key,$val)=each($stemmed_keywords)){ if($val<>" " and strlen($val) > 1){ $query .= $val."*"; $search_keys .= $val."* "; } } $query .= "' IN BOOLEAN MODE) AS score FROM articles art,galeries gal WHERE gal.`ARTICLE_ID`=art.`ARTICLE_ID` AND MATCH(art.`TITLE`,art.`DESCRIPTION`,gal.`CONTENT`) AGAINST ('".$search_keys."' IN BOOLEAN MODE))"; $query .= " UNION (SELECT DISTINCT `TEMPLATE`,`ARTICLE_ID`,`TITLE`,`DESCRIPTION`,MATCH(`TITLE`,`DESCRIPTION`,`CONTENT`) AGAINST ('".$search_keys."' IN BOOLEAN MODE) AS score FROM articles WHERE (MATCH(`TITLE`,`DESCRIPTION`,`CONTENT`) AGAINST ('".$search_keys."' IN BOOLEAN MODE))) ORDER BY score DESC LIMIT ".intval($start_row).",".$ammount; $rs = $this->dbActions->execQuery($query); $this->dbActions->execQuery("INSERT INTO searches (`KEY`,`DATE`,`RESULTS`) VALUES ('".$search_key."',NOW(),".$pages.")"); $search_results = "<div id='results'>"; while($row = mysql_fetch_array($rs)){ $search_results.= "<div id='result'>"; $search_results.= "<div class='result_title'><h4><a href='article.php?articleId=".$row["ARTICLE_ID"]."'>".$row['TITLE']."</a></h4></div>"; $search_results.= "<div class='result_description'>".$row['DESCRIPTION']."</div>"; $search_results.= "</div>"; $search_results.= "<div class='result_seperator'></div>"; } $search_results .= "</div>"; $return_val = $search_results; return $return_val; } dbactions class: require 'includes/errors.php'; error_reporting(0); class DBActions{ var $dbCon; var $errorHandler; function DBActions(){ $this->dbCon = $this->dbCon(); $errorHandler = new errors(1); } private function dbCon(){ require 'conf/configuration.php'; $dbcon = mysql_connect($dbUrl,$dbUser,$dbPass); if(!$dbcon)trigger_error("Unable to connect to database $dbUrl for user $dbUser",E_USER_ERROR); mysql_select_db($dbName); mysql_query("SET NAMES 'UTF8'"); mysql_query('set character set utf8'); return $dbcon; } function dbClose(){ if($this->dbCon) mysql_close($this->dbCon); } function execQuery($query){ $result = mysql_query($query,$this->dbCon); $msg = "Unable to execute query ".$query; if(mysql_num_rows($result) > 0) return $result; else if($result == false) trigger_error($msg,E_USER_ERROR); else return $result; } function send_error_mail(){ $this->errorHandler->sendErrorEmail(); } } I've try everything but can't get this working.. Any healp whould be really appreciated. Thanks in advance. Hey guys, so I have this script:
<?php $databasehost = "localhost"; $databasename = "import"; $databasetable = "import"; $databaseusername="import"; $databasepassword = "password"; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "test.csv"; if(!file_exists($csvfile)) { die("File not found. Make sure you specified the correct path."); } try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); } $affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." REPLACE INTO TABLE `$databasetable` FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator)); echo "Loaded a total of $affectedRows records from this csv file.\n"; ?> Hi, I have a sql query that executes perfectly in phpMyAdmin but when applied to a PHP script returns nothing. It won't even start a "while" loop. Please review code snippits below. Submission Script calls function in Database Class: $result = $database->testReturnId($_POST['years'], $_POST['model']); while($row = mysql_fetch_array($result)) { $i = $i + 1; echo "ROW " . $i . " " . $row['auto_id'] . " " . $row['auto_year'] . " " . $row['auto_year_high'] . " " . $row['auto_make'] . " " . $row['auto_model'] . "<br />"; } Database Class Function: function testReturnId($year, $model){ global $form; $q = 'SELECT * FROM tbl_svc_auto WHERE auto_model = "$model" AND "$year" BETWEEN auto_year AND auto_year_high'; if(!mysql_query($q, $this->connection)){ return false; }else{ return $result = mysql_query($q, $this->connection); } } I have moved the query to the submission script and replaced the variables with actual data and it still will not work. I can take the same query with out the variables and input it into phpMyAdmin and it works great. On the submission script, I added a row number to the echo thinking that it would a least return the word "ROW" and it does not. I have tested each step of the execution of the query and have not returned any errors. I do not receive any errors at all even during execution. It just seems to refuse to run the "while" statement. I do not know where my problem is......Please help. Thank you in advance for any assitance you can offer. Joshua Hello, I am trying to pick up php again and just exercising my skills. So I have it so that it fills my form with the values of what I want to edit, and when I click the edit button, it doesn't edit any of the information. When I echo out $result, I get a MYSQL query string that has the same values as the table, so its not getting the new values that are edited. <?php @mysql_connect('localhost', 'root', '') or die("Could not connect to Mysql Server. " . mysql_error()); @mysql_select_db('tutorials') or die("Could not connect to Database. " . mysql_error()); if(isset($_GET['edit'])) { $id = $_GET['edit']; $query = "SELECT `username`, `password` FROM `users` WHERE `id` = '$id'"; $result = mysql_query($query); $row = mysql_fetch_array($result); $name = $row['username']; $password = $row['password']; } if(isset($_POST['edit'])) { $id = $_GET['edit']; $query = "UPDATE `users` SET `username` = '$name', `password` = '$password' WHERE `id` = '$id'"; $result = mysql_query($query); echo $query; if(!$result) { echo mysql_error(); }else{ echo 'updated post'; } } ?> <form method="POST" action="" > <input type="text" name="name" value="<?php echo $name; ?>" /> First name <br /> <input type="text" name="password" value="<?php echo $password; ?>" /> Last name <br /> <input type="submit" name="edit" value="edit" /> </form> I believe it has something to do with the values of $name and $password in the form conflicting with the first if isset and the second if isset. Thanks for any help possible If you also have any feedback on my code, please do tell me. I wish to improve my coding base. Basically when you fill out the register form, it will check for data, then execute the insert query. But for some reason, the query will NOT insert into the database. In the following code below, I left out the field ID. Doesn't work with it anyways, and I'm not sure it makes a difference. Code: Code: [Select] mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); Full code: Code: [Select] <?php include_once("includes/config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <h2>Create</h2> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $name = mysql_real_escape_string($_POST['name']); $server_type = mysql_real_escape_string($_POST['type']); $description = mysql_real_escape_string($_POST['description']); if(!$username || !$password || !$server_type || !$description || !$name) { echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings!<br/>All forms are required to be filled out.<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40' name='description'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = mysql_query("SELECT username,name FROM servers WHERE username = '$username' OR name = '$name' LIMIT 1"); if(mysql_num_rows($check1) < 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); echo "Server has been succesfully created!"; } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> I'm restarting this under a new subject b/c I learned some things after I initially posted and the subject heading is no longer accurate. What would cause this behavior - when I populate session vars from a MYSQL query, they stick, if I populate them from an MSSQL query, they drop. It doesn't matter if I get to the next page using a header redirect or a form submit. I have two session vars I'm loading from a MYSQL query and they remain, the two loaded from MSSQL disappear. I have confirmed that all four session vars are loading ok initially and I can echo them out to the page, but when the application moves to next page via redirect or form submit, the two vars loaded from MSSQL are empty. Any ideas? Hey all I am almost done with my custom script and need one thing. Here is my code: Code: [Select] $con = mysql_connect(DB", "XXXX", "XXXX"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("XXXXXXX", $con); $name = $_POST['name']; $result = mysql_query("SELECT * FROM track WHERE name LIKE '%$name%'"); $num_rows = mysql_num_rows($result); while($row = mysql_fetch_array($result)) { echo $row['id']; echo $row['name']; echo $row['phone']; } ?> The above works good but currently if the user submits the form empty it still pulls all the names in the database due to the "like" use. I need to use like in this way because I need to be able to search partial names. How can I make it stay the exact same but ignore the query results if its NULL or empty? Thanks! ?> at the end of the script is not bright red. how can i fix it as it seems to be linked with the body text as its the same burgundy colour following on from my my php form error thread Hi, Relative newbie here pulling his hair out! I've just started to attempt to build a stock control system for my parent's business and am having problems. I'm building a (what I though) simple page that will just return all the info from a table. Each stock item has it's own stock code (5 characters) and also a barcode. There may be more than one barcode assigned to each stock item so I created a seperate table with just two fields - barcode and stockcode - the barcode obviously has to be unique but the stockcode doesn't. The way I have done it is with a form where you can enter the stock code - this then becomes $STOCKCODE and the rest of the page displays the result for that code - so far so good. Now I want it to see if the data entered into the form is greater than 5 characters. If it is it will then assume that you have entered a barcode and look for the stockcode from the other table and assign that to $STOCKCODE instead. The code below is the part that isn't working. Entering a stock code brings up the correct result, but enter a barcode and it just returns an incorrect product (always the same incorrect product irrespective of what you type in). Executing the barcode lookup query directly in mysql on it's own works and generates the correct stock code but there's something awry in the way I've done it that I can't seem to work out. The "echo "not recognised" at the end doesn't work either. Googling the problem had just confused me even more! Any help would be appreciated! Cheers Code: [Select] //retrieve form result $getcode=$_POST['item_entry']; //Count characters in form result $num_char=strlen($getcode); //barcode lookup query $result = mysql_query("SELECT barcode.SKU FROM barcode WHERE $getcode = 'barcode.BARCODE'"); //se if the entered data was a stockcode or a barcode if ($num_char == 5) {$STOCKCODE=$getcode;} elseif ($num_char > 5) {$STOCKCODE=mysql_fetch_assoc($result);} else echo "not recognised"; Hello! Please help... I am trying to use the script below to get results from a mysql database based on a query of the form fields (the names of which are displayed near the top of the script as POST items) When a location or age etc. is entered into the form, I want the script to search for records which meet those criteria. At the moment the script works but only does so if all the values are entered to match what is in the database. e.g. if the location england and the age 22 was entered into the form, and that matched the value in the database, then at the moment, the script will display the result, but if only the location is entered in the form without any value for age/genre etc. then no results are displayed. Any help would be very welcome as I have search high and low for a solution on google... which doesn't seem to exist... I'm not that experienced with php/mysql but am learning on the job so any helpful prompts as to terms etc. would help! Thanks! Lewis <?php if($_POST) { $searchage = $_POST['searchage']; $searchlocation = $_POST['searchlocation']; $searchgenre = $_POST['searchgenre']; $searchinstrument = $_POST['searchinstrument']; $searchexperience = $_POST['searchexperience']; // Connects to your Database mysql_connect("localhost", "user", "pass") or die(mysql_error()); mysql_select_db("DB") or die(mysql_error()); $query = mysql_query("SELECT * FROM table_user WHERE userage = '".$searchage."' AND userlocation = '".$searchlocation."' AND usergenre = '".$searchgenre."' AND userinstrument = '".$searchinstrument."' AND userexperience = '".$searchexperience."'") or die(mysql_error()); $num = mysql_num_rows($query); echo "$num results found!<br>"; while($result = mysql_fetch_assoc($query)) { $username = $result['username']; $useremail = $result['useremail']; $userage = $result['userage']; $userlocation = $result['userlocation']; $usergenre = $result['usergenre']; $userinstrument = $result['userinstrument']; $userexperience = $result['userexperience']; $userbiography = $result['userbiography']; echo " Name: $username<br> Email: $useremail<br> Age: $userage<br> Location: $userlocation<br> Gen $usergenre<br> Instrument: $userinstrument<br> Experience: $userexperience<br> Biography: $userbiography<br><br> "; } } ?> I have the following MYSQL Query: Basically, the query will not work when i add quotes to the string. I want it to select from e-mails database where subject LIKE '%"$stringservername"%' If I do just '%$SERVERNAME%' it works :S - And the mysql data includes the quotes. I use the $strongservername to add the quotes. $stringservername = ""$servername""; $stringjobname = ""$vjobname""; $queryemails = mysql_query("SELECT * FROM `emails` WHERE `subject` like '$searchstatus' AND `subject` like '%$stringservername%' AND `subject` like '%$stringjobname%' AND `fromemail` = '$matchfrom'"); Any suggestions? Thankyou Hi there, I am executing this query in the code below, it executes as I want it except when it gets the title, it doesnt get the title for that row it just gets it from the first row in the table... if that makes sense... what is going on? Code: [Select] <?php require'styles/top.php'; ?> <br> <center><table border='0' width='100%' style='text-align:center; font-weight:bold;'> <tr> <td width='33%'>Subject</td> <td width='33%'>From</td> <td width='33%'>Date</td> </tr> </table></center> <br> <?php $query = mysql_query("SELECT * FROM messages WHERE to_user='$username' ORDER BY message_id DESC") or trigger_error('Error: ' . mysql_error()); $numrows = mysql_num_rows($query); if ($numrows > 0){ while ($row = mysql_fetch_assoc($query)){ $id = $row['message_id']; $from = $row['from_user']; $to = $row['to_user']; $title - $row['message_title']; $content = nl2br($row['message_content']); $date = $row['date']; echo"<center><table border='0' width='100%' style='text-align:center; font-weight:bold;'> <tr> <td width='33%'>$title</td> <td width='33%'>$from</td> <td width='33%'>$date</td> </tr> </table></center> <br>"; } } else echo ''; ?> </div> <div id='left'> </div> <div id='right'> </div> I have this query that searches the database based on what the user inputed. However i'm having the following issues with it: The query is supposed to look for the name of a city in a database table that stores the city names along with their state and country CITY STATE COUNTRY Now i have an input field where the user can search a location and it searches the location from the database. When they search the database the input is in the following format: city, state, country I then use the following script to separate them into three fields Code: [Select] $split = explode(',', $location); // $location being the city, state, country $city = $split[0]; $state = $split[1]; $country = $split[2]; Then i use this MySql Query to search the fields to make sure the city and country match Code: [Select] $get_location = mysql_query("SELECT * FROM locations WHERE name LIKE '$city' AND country LIKE '$country'") or die(mysql_error()); $tmp_loc = mysql_fetch_assoc($get_location); This is where the problem beings...if i use "AND" to search both fields i get no results even though there are results in there however if i change it to an "OR" statement it finds teh locations however it doesn't do an accurate search... for example someone searches for Toledo, Ohio, United States, the user will get Toledo, Spain instead of the right Toledo, since Toled, Spain is at the top of the table I've been trying to get this but i can't get this to work at all every time i use AND it gives me no results I hope someone here can check help me out I am creating a site that has to display 36 images on the screen. The image name is stored in the database. My problem is if I have less than 36 images stored I need to display a default image. here is my current query $sql="SELECT col_image, col_url from tbl_images WHERE col_active='1' and col_bigimage='0' ORDER BY RAND() limit 36"; so If I only have 20 active images. I need to display 16 default images. I hope this makes sense. Bill Hi all, I have a database with 2 tables, 'users' and 'battles'. The site pulls 2 random peoples pictures and lets the user choose who they think would win the battle. So if user1 is using the site it might show pictures for user5 and user3. If the user1 chooses that user5 wins then an entry is made into the 'battles' table like this : voter win lose user1 user5 user3 Any ideas what query I can use so it only shows 2 people that the user hasnt compared before ? As if its doing this : choose 2 id's from 'users' that user1 hasnt compared before Hope that makes sense. Many thanks, Scott Hi Guys, I have been having problems with a piece of PHP and mysql. I was wondering if you could help me out? The error is = Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /customers/klueless.net/klueless.net/httpd.www/daisysite/home.php on line 120 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /customers/klueless.net/klueless.net/httpd.www/daisysite/home.php on line 122 And this is the code which goes with these errors = Code: [Select] $msgquery = "SELECT * FROM spotty_messages WHERE (id_receiver = '" . $userid . "') AND read = '0'"; $messageres = mysql_query($msgquery); $messrow = mysql_fetch_array($messageres); $messagecount = mysql_num_rows($messageres); hi dudes how do i write a mysql query with 3 columns, where the first column is 'year', the second is 'month' (integer) and the third is 'day' (integer), ordered by desc, but with an extra quirk, where if any of the three columns is zero (which means there is no data for that date column - assume i have a year and a month, but no day)? my code looks like the following Code: [Select] ORDER BY exhib_date_year DESC, exhib_date_month DESC, exhib_date_day DESC Hi All, Wondered if someone could help me out with a sql query that I am having difficulty with? My database consists of 3 tables, clients, video, category. The video table stores the primary key value of the clients table and the category table as a foreign key. What I am trying to achieve is return all the videos that are associated to a particular client and group them under the relevant category. If there are now videos that match the category then I do not want to display the category. Here is my code so far: Code: [Select] <?php $sql = "SELECT category.cat_id, category.name AS catname FROM category"; $result = mysql_query($sql) or die (mysql_error()); while($categoryrow = mysql_fetch_assoc($result)) { ?> </p> <div class="themeheader"><h5><?php echo $categoryrow['catname']; ?></h5></div> <Br /> <?php $vsql = "SELECT video.video_id, video.title, video.description, video.thumbnail FROM video WHERE video.cat_id = '" . $categoryrow['cat_id'] . "' AND video.client_id = $customerid ORDER BY video.video_id DESC"; $vresult = mysql_query($vsql) or die (mysql_error()); ?> <div class="videos"> <ul> <?php while($videorow = mysql_fetch_assoc($vresult)) { ?> <li id="categoryList"><a href="film-details.php?video_id=<?php echo $videorow['video_id']; ?>"><img src="+_1m4g35/<?php echo $videorow['thumbnail']; ?>" alt="<?php echo $videorow['title']; ?>" title="<?php echo $videorow['title']; ?>" width="291" height="142" border="0" /></a> <h2><?php echo $videorow['title']; ?></h2> <p><?php $limit = 100; if (strlen($videorow['description']) > $limit) $description = substr($videorow['description'], 0, strrpos(substr($videorow['description'], 0, $limit), ' ')) . '... <a href="film-details.php?video_id='.$videorow['video_id'].'">read more</a>'; echo $description; ?> </p> <?php } //end video loop?> </ul> <br class="clearfloat" /> </div> <?php } //end category loop ?> </div> The above code is the closest I have got but it still outputs the categories even when there are no videos that match the category id and the client id. Any help in the right direction gratefully received as I am gradually going insane! $loc="SELECT * FROM table WHERE username='a', id='1' AND uin='123'"; $get=myspl_query($loc) or die(mysql_error()); Please somone tell me the right command as how to use multiple AND in mysql query. Thanks |