PHP - Do A Select On Two Tables And The Result Allows Access To Fields Of These Two Selected Tables
Im doing a search system and Im having some problems.
I need to search in two tables (news and pages), I already had sucess doing my search system for just one table, but for two tables its not easy to do.
I already use a select statment with two tables using UNION because I want to show number of search results, that is number of returned rows of my first sql statment.
But now I need to do a select statment that allows me to acess all fields of my news table and all fields of my pages table.
I need to acess in my news table this fields: id, title, content, link, date, nViews
I need to acess in my pages table this fields: id, title, content, link
Im trying to do this also with UNION, but in this case Im not having any row returning.
Do you see what I have wrong in my code?
<?php
//first I get my $search keyword $search = $url[1]; $pdo = connecting(); //then I want to show number of returned rows for keyword searched $readALL = $pdo->prepare("SELECT title,content FROM news WHERE title LIKE ? OR content LIKE ? UNION SELECT title,content FROM pages WHERE title LIKE ? OR content like ?"); $readALL->bindValue(1,"%$search%", PDO::PARAM_STR); $readALL->bindValue(2,"%$search%", PDO::PARAM_STR); $readALL->bindValue(3,"%$search%", PDO::PARAM_STR); $readALL->bindValue(4,"%$search%", PDO::PARAM_STR); $readALL->execute(); //I show number of returned rows echo '<p>Your search keyword returned <strong>'.$readALL->rowCount().'</strong> results!</p>'; //If dont return any rows I show a error message if($readALL->rowCount() <=0){ echo 'Sorry but we didnt found any result for your keyword search.'; } else{ //If return rows I want to show, if it is a page result I want to show title and link that I have in my page table //if it is a news result I want to show title and link that I have in my news table and also date of news echo '<ul class="searchlist">'; $readALL2 = $pdo->prepare("SELECT * FROM news WHERE status = ? AND title LIKE ? OR content LIKE ? LIMIT 0,4 UNION SELECT * FROM pages where title LIKE ? OR content LIKE ? LIMIT 0,4"); $readALL2->bindValue(1, '1'); $readALL2->bindValue(2, "%$search%", PDO::PARAM_STR); $readALL2->bindValue(3, "%$search%", PDO::PARAM_STR); $readALL2->bindValue(4, "%$search%", PDO::PARAM_STR); $readALL2->execute(); while ($result = $readALL2->fetch(PDO::FETCH_ASSOC)){ echo '<li>'; echo '<img src="'.BASE.'/uploads/news/'.$result['thumb'].'"/>'; echo '<a href="'.BASE.'/news/'.$result['id_news'].'">'.$result['title'].'</a>'; //if it is a news result I also want to show date on my list //echo '<span id="date">'.$result['date'].'</span>'; echo '</li>'; } echo ' </ul>'; //but how can I do my select statement to have access to my news table fields and my page table fields?? } ?> Similar TutorialsI need help connecting to a Visual FoxPro 9 Database and Table via php. I know this is possible because I've read of people doing this but I still have no resolve on this issue. Does anyone know of anyway to connect to a VFP9 table via php? I would like step by step instructions on how to handle this including any server dependencies or installations needed to make this work. (Server: Linux, webserver, Apache, PHP) (Visual Foxpro Database is in another location in a windows machine.) hirealimo.com.au/code1.php this works as i want it: Quote SELECT * FROM price INNER JOIN vehicle USING (vehicleID) WHERE vehicle.passengers >= 1 AND price.townID = 1 AND price.eventID = 1 but apparelty selecting * is not a good thing???? but if I do this: Quote SELECT priceID, price FROM price INNER JOIN vehicle....etc it works but i lose the info from the vehicle table. but how do i make this work: Quote SELECT priceID, price, type, description, passengers FROM price INNER JOIN vehicle....etc so that i am specifiying which colums from which tables to query?? thanks To access MySql tables from PHP, I use the PHP code and the function below. If I make these changes, would this code work for SQL Server 2008? mysql_fetch_array to mssql_fetch_array mysql_connect to mssql_connect mysql_select_db to mssql_select_db mysql_query to mssql_query PHP code -------------------------------------------------------------------------------- $sql = "SELECT mast_id FROM district_mast WHERE mast_district = '".$dist_num."'"; $result = func_table_access($sql); $rows = mysql_fetch_array($result); Function -------------------------------------------------------------------------------- FUNCTION func_table_access($sql) { $db = "aplustutoru"; $host = "localhost"; $user = "root"; $pass = ""; IF (!($conn=mysql_connect($host, $user, $pass))) { PRINTF("error connecting to DB by user = $user and pwd=$pass"); EXIT; } $db3 = MYSQL_SELECT_DB($db,$conn) or die("Unable to connect to local database"); IF ($sql <> "justopendb") { $result = MYSQL_QUERY($sql) OR DIE ("Can not run query because ". MYSQL_ERROR()); RETURN $result; } } i have two tables Loan Application table and Loans table. There is status option and date loan was applied section. After status has been chosen as Pending from the dropdown field and date chosen and loan application saved, it goes under the loans section. Now, admin has to go and approve the loan and pick the date the loan was approved under the loans section but date can be chosen for the approved date but the status cant be changed to approve because it shows pending. Please what can i do so when i select the date for approval , the status should change to approved automatically Hi can anybody help I need to export and download tables from a database into a excel sheet. I have this code and it works what I need is to export specific fields and not just the whole table can anyone help modifying the code to export certain fields within the table please? Here is the code... Code: [Select] <?php $host = 'localhost'; $user = 'user'; $pass = 'password'; $db = 'qdbname'; $table = 'tablename'; $file = 'export'; $link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error()); mysql_select_db($db) or die("Can not connect."); $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field']."; "; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j]."; "; } $csv_output .= "\n"; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; ?> HI, I have a ms-access file which has linked table. The linked table is connected to a ODBC source (e.g MS-SQL or 3rd Party ODBC Driver). WebPage(php) Apache, connecting to a ODBC DSN of MS-Access, MS-Access is having linked tables. Linked tables as from another ODBC source. On the PHP Page, When I am trying to connect the ms-access odbc dsn , I am able to connect. But when I query any of the linked tables, PHP is not able to query and is failing. Does php has capabilities to read/write to linked tables in ms-access file. Or it is issue with MS-Access Or is it I am missing something. Microsoft says, its an issue of PHP https://social.msdn....forum=accessdev Requesting you to please share your feedback Regards Rajendra Dewani Hi, i have a database with multiple records. One of those values is an image. When i query the database and i want only the images as a result it gives the result in a field. It then fills up the field horizontal and when there is no more field left it starts a new row. That is what i want. But now i want some extra info next to the picture so i put that in a table with two colums like this: echo '<table border="1" width="400"><td><a href="'.$row['website'].'"> <img src="'.$row['prod_img'].'"> '.$row['prod_name'].' <a href="'.$row['website'].'">'.$row['website'].'</td></table> ';}} But i still want the result to fill up the field and when the field is full i want the next results on a row below this.... Anyone? I have a relational table call sales with prodcut_id and custmer_id tables. I also have a product and customer tables. products table with product_id as an auto increment and customer with custumer_id I want to join through the sales tables all t he fields of row 1 from tables customer and products and pull it at once. This is a member login script and I want to display the products by members. So far I have this query to display the products once the member is login in. $userid is the id of the customer coming from the $userid= $_SESSION['customer_id']; $mysqlSales="SELECT products.* FROM products JOIN sales ON (products.product_id = procuct_id ) WHERE sales.customer_id = '$userid'"; so far that statement is not working where should I have some type of incoherance with the english statement above expressing what I want the query to do. I am trying to simplify my coding work for my website and wanting to make it operate more professionally (as part of my training to better my programming skills, which I know will take a lot of time to do). One of the things I`d like to improve on it is to create tables and fields in my mysql database, but not have to go into phpmyadmin to do it. I know open source programs like Drupal can do this easily so that when you add modules, the user does not have to access the database to set it up. But looking at the codes, I`m unable to figure out how it works. How will I be able to program my code to do something like, I`ll have a form where I enter in what I want the new table to be called, what fields to add in and their specifications, where I could do this by just going into my website as the admin? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=332033.0 hey, i trying to select * colums form one table and 1 colum from another table... this is my code: Code: [Select] $DB->query("SELECT m.*, v.time, v.viewerid FROM members m LEFT JOIN profile_views v ON (m.id=v.userid) WHERE m.id IN ({$viewers_ids})"); but sometimes this query return multiply rows... any ideas? Thanks! Hi there I have 2 tables: Fleet FleetName PlanetName Status Planet PlanetName PlayerName Im trying to write a select query that will search through the fleet table and display Fleet table details Where the PlanetName from the fleet table is = to the PlanetName of the Planet table. Ive tried joining the tables but i dont think the logic quite works.. Code: [Select] mysql_select_db($database_swb, $swb); $query_Fleet = sprintf("SELECT fleet.FleetName, planet.PlanetName FROM fleet, planet WHERE fleet.PlanetName = planet.PlanetName"); $Fleet = mysql_query($query_Fleet, $swb) or die(mysql_error()); $row_Fleet = mysql_fetch_assoc($Fleet); $totalRows_Fleet = mysql_num_rows($Fleet); I want ONLY the Fleets from the planet i am looking at to be displayed not all of them. I have created another query that displays the planet name of the particular one I am looking at as it is parsed from a hyperlink on a previous page. So is there some way i can use both queries together? "SELECT FROM fleet, WHERE $fleet.PlanetName = $planet.PlanetName" Im a little bit confussed, please help hey, i'm trying to select information from 2 tables in one query... so i have 2 tables... members - (holds the members information) looks like this: Code: [Select] +---+--------+------------+------------+ | id | name | email | password | +---+--------+------------+------------+ | 1 | user1 | 1@g.com | **** | | 2 | user2 | 2@g.com | **** | | 3 | user3 | 3@g.com | **** | | 4 | user4 | 4@g.com | **** | | 5 | user5 | 5@g.com | **** | | 6 | user6 | 6@g.com | **** | +---+--------+------------+------------+ the second table is profile_views which stores the profile views... Code: [Select] +---+--------+-----------+---------------+ | id | userid | viewerid | time | +---+--------+-----------+---------------+ | 1 | 4 | 1 | 1287949172 | | 2 | 6 | 2 | 1287949172 | | 3 | 2 | 4 | 1287949172 | | 4 | 4 | 5 | 1287949172 | | 5 | 3 | 2 | 1287949172 | +---+--------+-----------+---------------+ userid - the profile (member) id that been watched viewerid - the id of the member who watched time - the time this happened im trying to select from profile_views the viewers ids' and select the info from the members according to the viewerid, but also i want to select the time from the profile_views, so it's should look like this: Code: [Select] +---+--------+------------+----------+------------+ | id | name | email | password | time +---+--------+------------+----------+------------+ | 1 | user1 | 1@g.com | **** | 1287949172 | 2 | user2 | 2@g.com | **** | 1287949172 | 3 | user3 | 3@g.com | **** | 1287949172 | 4 | user4 | 4@g.com | **** | 1287949172 | 5 | user5 | 5@g.com | **** | 1287949172 | 6 | user6 | 6@g.com | **** | 1287949172 +---+--------+------------+----------+------------+ this is my code: Code: [Select] $DB->query("SELECT viewerid FROM profile_views WHERE userid={$core->input['showuser']} ORDER BY time DESC LIMIT 5"); if ( $DB->get_num_rows() > 0 ) { while ( $all_viewers = $DB->fetch_row() ) { $viewers_ids[] = $all_viewers['viewerid']; } $viewers_ids = implode(",", $viewers_ids); $DB->query("SELECT m.*, v.* FROM members m LEFT JOIN profile_views v ON (v.userid=m.id) WHERE m.id IN ({$viewers_ids})"); while ( $viewers = $DB->fetch_row() ) { } } but it's just dont work! any ideas? Thanks in advance! I'm having a hard time grasping how to select data from several tables. Here's the code Code: [Select] <?php require_once "config.php"; $gamedate = $_SESSION['date']; echo "These umpires are not currently scheduled on this date, and have not asked for the day off:<br />"; $umpirelist = Array('umpire 1 name', 'umpire 2 name', 'umpire 3 name'); $dbc = mysql_pconnect($host, $username, $password); mysql_select_db($db,$dbc); foreach($umpirelist as $data) { //now get stuff from a table $sql = "SELECT calendar.date, calendar.ump1, calendar.ump2, calendar.ump3, calendar.ump4, calendar.ump5, vacation.date, vacation.umpire FROM umps, calendar, vacation WHERE umps.full_name = $data AND $gamedate = `calendar.date` AND $gamedate = `vacation.date` AND $data NOT IN ('calendar.ump1', 'calendar.ump2', 'calendar.ump3', 'calendar.ump4', 'calendar.ump5') AND $data NOT IN ('vacation.umpire') order by umps.full_name asc"; $rs = mysql_query($sql,$dbc); $matches = 0; while ($row = mysql_fetch_assoc($rs)) { $matches++; echo "$row[$data]<br />"; } } ?> The table CALENDAR holds the date of the game, who is playing, and what umpires are schedule for that game. it does have a unique "row_number" column as well, but didn't think I'd need it in this select. The table VACATION has the date, and umpire's name that is on vacation. The table UMPS contains the umpires name (same names as the array in the code) and email addresses and login info. I'm getting this error: Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource on line 152 This is line 152 Quote while ($row = mysql_fetch_assoc($rs)) { Can someone please point me in the right direction as to where I'm going wrong? Thanks! Hi guys, This is my first time posting here - im just getting into PHP - i got a question; I have two databases: profile(id, name, interests, dob, gender, join_date, email) interests(id, profile_id, interests) id being the primary key, and profile_id being the foreign key from profile. I want to script that returns profile information and all the matching interests (one user can have multiple interests). This is what i have so far, though it does not work, and i knew it wouldnt; function get_profile($id) { $connection = mysql_open(); $query = "SELECT * "; $query .= "FROM profiles, interests "; $query .= "WHERE profile.id=" . $id; $query .= " AND interests.profile_id=" . $id; $result = @ mysql_query($query, $connection); // Transform the result set to an array (for Smarty) $entries = array(); while ($row = mysql_fetch_array($result)) { $entries[] = $row; } mysql_close($connection) or show_error();; return $entries; } Can someone please advise on how this can be done? or do i need to have two query's one for each table ? Thank you in advance!! This topic is now in MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=357554.0 hi im trying to echo out all the possibilities from one column in 2 different tables, both with the same structure. if that makes sense this is what i have $query = mysql_query("SELECT * FROM stanjamesprem,centrebetprem GROUP BY eventname ORDER BY eventtime "); while($row = mysql_fetch_assoc($query)) { echo $row[eventname]; } if i take one of the tables out it works fine but if i have 2 table names it doenst work please help me cheers matt any questions please ask away Hi ho, I am trying to assemble a table so that it shows article in order by id descending. The current one i am using is working but not displaying as i hoped, i need them aligned on the left and right, so id=1 align left, id=2 align right etc. Here's my current code Code: [Select] <table style='table-layout:fixed' align="center" cellpadding="2" cellspacing="0" colspan="" class="Main"><br> <? $select_paper=mysql_query("SELECT * FROM paper ORDER BY id DESC"); while($the=mysql_fetch_object($select_paper)){ ?> <tr> <td class="subtableheader" width="25%"><?php echo "$the->title"; ?></td> </tr> <tr> <td class="profilerow" width="100%"><?php echo "$the->news"; ?></td> </tr> <tr> <td class="subtableheader" width="25%"><?php echo "Article By $the->by - $the->date"; ?></td> </tr> I want to select the user from super_administrators, administrators, teachers and students, and give the user permission based from what table he "came". But is giving the "Query failed" error... Code: [Select] <?php //Start session session_start(); //Include database connection details require_once('../config/config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $email = clean($_POST['email']); $password = clean($_POST['password']); //Input Validations if($email == '') { $errmsg_arr[] = 'O campo Email nao foi preenchido.'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'O campo Senha nao foi preenchido.'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } //Create query $qry = "SELECT * FROM super_administrators,administrators,teachers,students WHERE email = '$email' AND passwd = '".md5($_POST['password'])."'"; $result = mysql_query($qry); $member = mysql_fetch_assoc($result); $table = mysql_field_table('$result', '0'); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { if($table == 'super_administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/sadmin/index.php"); exit(); } if($table == 'administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/admin/index.php"); exit(); } if($table == 'teachers') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/prof/index.php"); exit(); } if($table == 'students') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_CLASS_ID'] = $member['class_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_REGISTRATION'] = $member['registration']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/aluno/index.php"); exit(); } } else { $errmsg_arr[] = 'Suas informacoes de login estao incorreta. Por favor, tente novamente.'; $errflag = true; $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } } else { die("Query failed"); } ?> I have 2 tables I have settup called Users_Messages and Users_Message_Replies inside each of these tables I have a row called DateSent, I'm trying to select from both of these tables and only display the latest Sent item by ID and order them all by date. I can get it to display the items correctly using the below code, but I can't get them to order correctly by the latest date in both of the Tables. Code: [Select] $page_query = mysql_query(" SELECT MessageID, DateSent FROM Users_Messages WHERE ToID = '$user_ID' UNION SELECT MessageID, DateSent FROM Users_Messages WHERE FromID = '$user_ID' ORDER BY DateSent DESC "); while ($replycheck = mysql_fetch_assoc($page_query)){ $message_idmainnew = $replycheck['MessageID']; $date = $replycheck['DateSent']; $sql2 = "SELECT MainMessageID FROM Users_Message_Replies WHERE MainMessageID = '$message_idmainnew '"; $sql_result2 = mysql_query($sql2); $replycheck2 = mysql_fetch_assoc($sql_result2); $newreplyID = $replycheck2['MainMessageID']; $sql4 = "SELECT MessageID FROM Users_Messages WHERE MessageID= '$message_idmainnew'"; $sql_result4 = mysql_query($sql4); $messagecheck2 = mysql_fetch_assoc($sql_result4); $newmessageID = $messagecheck2['MessageID']; if ($newreplyID == NULL){ $sql2 = "SELECT * FROM Users_Messages WHERE MessageID= '$newmessageID' ORDER BY DateSent ASC"; $sql_result2 = mysql_query($sql2); $message_row = mysql_fetch_assoc($sql_result2); $message_01 = $reply_row['Message']; $date = $reply_row['DateSent']; $date1 = strtotime($date); $datemain = date('F j, Y, g:i a', $date1); }else{ $sql2 = "SELECT * FROM Users_Message_Replies WHERE MessageID= ' $newreplyID ' ORDER BY DateSent DESC"; $sql_result2 = mysql_query($sql2); $reply_row = mysql_fetch_assoc($sql_result2); $message_01 = $reply_row['Message']; $date = $reply_row['DateSent']; $date1 = strtotime($date); $datemain = date('F j, Y, g:i a', $date1); } { Is there an easier way to do this? And how would I get the dates to line up, with a Join? Thanks. |