PHP - Php Variable In A Query With Like Condition Syntax Question
I have a query:
$query ="select * FROM telephone_admin where name Like ' ".$_GET['answer']." ' "; I would like to add % before and after so that the query will search for result which contains the PHP variable $_GET['answer'] before or after, but the problem is how can I add % before or after ' ".$_GET['answer']." ' within the query?? Thanks! Similar TutorialsHi there, I am working on a PHP website. And I am running a query which checks for the expired products. We check to see if the expiry date is greater than the current systems date then display the record. It looks something like this: Code: [Select] select * from products WHERE products.productExpiry) >= '2010-10-13 00:00:00' 'productExpiry' field is of 'Datetime' Datatype And Expiry date is stored in database as: 2010-10-19 04:39:35 Now it works fine. But the problem only arises (no record shows) when there is no date in the 'productExpiry' field. How can I check or set a condition in my SQL query that whenever the 'productExpiry' is Null or Blank don't compare it with the current date. Please reply All comments and feedbacks are welcomed Thank you! I'm a bit of a newb to PHP and MySQL. I seem to be having an issue with something. How do I loop through an array, querying each value in the array until the query meets a certain condition.. In this case it would be that the number of rows returned from the query is less than five. Here is what I have: $query1="SELECT UserID FROM Users where RefID='$userid'"; $result1=mysql_query($query1); while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5') { echo ($row[0]); echo " "; $sql2 = "SELECT * FROM Users WHERE RefID=$row[0]"; $sql2result = mysql_query($sql2); $sql2querynum = mysql_numrows($sql2result); } Problem is, for every value it echoes out, I get the following warning: mysql_numrows(): supplied argument is not a valid MySQL result resource Like I said, I'm a newbie to PHP to maybe I'm not even going about doing this the right way. Hoping someone can help to point me in the right direction. I am trying to use the following query with sorting: $query = mysql_query("SELECT * FROM Table WHERE Date LIKE '$PeriodSelected' ORDER BY Date DESC"); $PeriodSelected is basically supposed to get me all results from month selected and it works fine. Now I am trying to add sorting to this query and although I get no errors it does not matter if I use ASC or DESC my results are sorted in the same way. Not sure what I am doing wrong. I have the following if statement: Code: [Select] if ((isset($select_category) == 'All') || (!isset($select_category)) && (!isset($most_liked))) { The value for the variable gets taken from a drop down menu, which is a list of categories. The problem I am having is with the isset condition check is that the variable is always set, but it does not consider the check for equality with the 'All' condition. Which basically means no matter which category I choose from the drop down menu, it always goes to this very first if statement, and does NOT go to the other elseif statement, and I think it has to do with the isset condition check, because without it it would work, though without it I am getting a notice warning, that the variables are undefined. Any ideas how I can make it check if its equal to 'All' together with the isset condition check? What I am trying to say is no matter which category is chosen, with the isset condition check, the variable is always set, thus the if statement is true, there basically seems to be a contradiction going on. [text]I created two tables in a database called 'members' and 'blogs'. The blogs table uses the primary key of the members table (member_id), as a foreign key. The member_id is an auto incremented column in the members table and when I query and print out the rows of this table, the member_id values for the two members I created, turn out to be 1 and 2 as expected. Now when I use a subselect query in an insert statement, to input member_id values into the blogs table, and then query the rows of this table, both member_id values show up as 0. I will display both tables and the insert query for the blogs table below. Can anyone identify the problem? I'm convinced there is something about the subselect query that I'm not getting right. Ill also include the select query that displays the results of the blogs table just in case. [/text] Code: [Select] <?php $query = "CREATE TABLE members ( member_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , username VARCHAR( 50 ) NOT NULL UNIQUE, firstname VARCHAR( 50 ) NOT NULL , lastname VARCHAR( 50 ) NOT NULL , title VARCHAR(10), password VARCHAR( 50 ) NOT NULL , primary_email VARCHAR(100), secondary_email VARCHAR(100), register_date DATE, ip VARCHAR( 50 ) NOT NULL , UNIQUE (username) )"; ?> <?php $query = "CREATE TABLE blogs ( blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , member_id INT UNSIGNED, like_id INT UNSIGNED, title VARCHAR( 500 ) NOT NULL, entry VARCHAR( 2000 ) NOT NULL , blog_date DATE )"; ?> <?php $query = "INSERT INTO blogs ( member_id, title, entry, blog_date) VALUES ( 'SELECT member_id FROM members', '{$_POST['title']}', '{$_POST['entry']}', NOW())"; ?> <?php $query= 'SELECT * FROM blogs'; if($r = mysql_query ($query)) {//Run the query. //Retrieve and print every record. while ($row = mysql_fetch_array ($r)) { print " {$row['title']}" ; print " {$row['entry']}" ; print " {$row['blog_date']}" ; print " {$row['member_id']}" ; } } else {//Query didn't run. die (' Could not retrieve the data becasue: .mysql_error(). '); }//End of query IF. mysql_close(); //Close the database connection. ?> Any help is appreciated. It's been a while since I sat down to build some pages and teach myself php. So now that I've started back up, I'm at a loss for what I've done. I deleted a file, and have to rebuild from an old broken version: I have a form that submits a query to the database, but the results pages is giving me this error: Code: [Select] Oops, my query failed. The query is: SELECT COUNT 'descriptors'.* ,'plantae'.* FROM 'descriptors' LEFT JOIN 'plantae' ON ('descriptors'.'plant_id' = 'plantae'.'plant_name') WHERE 'leaf_shape' LIKE '%auriculate%' AND 'leaf_venation' LIKE '%%' AND 'leaf_margin' LIKE '%%' The error is: 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 '.* ,'plantae'.* FROM ' at line 2 But I'm not seeing what the syntax error is. Here's the code: Code: [Select] <?php require ('connection.php'); $display = 2; // it's intentionally only 2 for the moment if (isset($_GET['np'])) { $num_pages = $_GET['np']; } else { $data = "SELECT COUNT 'descriptors'.* ,'plantae'.* FROM 'descriptors' LEFT JOIN 'plantae' ON ('descriptors'.'plant_id' = 'plantae'.'plant_name') WHERE 'leaf_shape' LIKE '%$s1%' AND 'leaf_venation' LIKE '%$s3%' AND 'leaf_margin' LIKE '%$s4%'"; $result = mysql_query ($data); if (!$result) { die("Oops, my query failed. The query is: <br>$data<br>The error is:<br>".mysql_error()); } $row = mysql_fetch_array($result, MYSQL_NUM); $num_records = $row[0]; if ($num_records > $display) { $num_pages = ceil ($num_records/$display); } else { $num_pages = 1; } } if (isset($_GET['s'])) { $start = $_GET['s']; } else { $start = 0; } if(isset($_POST[submitted])) { // Now collect all info into $item variable $shape = $_POST['s1']; $color = $_POST['s2']; $vein = $_POST['s3']; $margin = $_POST['s4']; // This will take all info from database where row tutorial is $item and collects it into $data variable $data = mysql_query("SELECT 'descriptors'.* ,'plantae'.* FROM 'descriptors' LEFT JOIN 'plantae' ON ('descriptors'.'plant_id' = 'plantae'.'plant_name') WHERE 'leaf_shape` LIKE '%$s1%' AND 'leaf_venation' LIKE '%$s3%' AND 'leaf_margin' LIKE '%$s4%' ORDER BY 'plantae'.'scientific_name` ASC LIMIT $start, $display"); //chs added this in... echo '<table align="center" cellspacing="0" cellpading-"5"> <tr> <td align="left"><b></b></td> <td align="left"><b></b></td> <td align="left"><b>Leaf margin</b></td> <td align="left"><b>Leaf venation</b></td> </tr> '; //end something chs added in // This creates a loop which will repeat itself until there are no more rows to select from the database. We getting the field names and storing them in the $row variable. This makes it easier to echo each field. while($row = mysql_fetch_array($data)){ echo '<tr> <td align="left"> <a href="link.php">View plant</a> </td> <td align="left"> <a href="link.php">unknown link</a> </td> <td align="left">' . $row['scientific_name'] . '</td> <td align="left">' . $row['common_name'] . '</td> <td align="left">' . $row['leaf_shape'] . '</td> </tr>'; } echo '</table>'; // row 95 } if ($num_pages > 1) { echo '<br /><p>'; $current_page = ($start/$display) + 1; // row 100 if ($current_page != 1) { echo '<a href="leafsearch2a.php?s=' . ($start - $display) . '&np=;' . $num_pages . '">Previous</a> '; } for ($i = 1; $i <= $num_pages; $i++) { if($i != $current_page) { echo '<a href="leafsearch2a.php?s=' . (($display * ($i - 1))) . '$np=' . $num_pages . '">' . $i . '</a>'; } else { echo $i . ' '; } } if ($current_page != $num_pages) { echo '<a href="leafsearch2a.php?s=' . ($start + $display) . '$np=' . $num_pages . '"> Next</a>'; } } //added curly ?> Have a ton of pop-up javascript links in my page. To tidy up the code, I have decided to declare all links at top of the page to keep them together and simply use the variable within the "a" brackets. Let me show you: Code: [Select] <? $brand_edit = 'javascript:void(0)"onclick="window.open('/admin/form.php?db=outlet&tbl=brands&auto_increment=<? echo $auto_increment; ?>&action=edtamp;step=1','none','width=750,height=250,menubar=no,status=no,resizable=no,location=no,toolbar=no,scrollbars=yes,left=50,top=50,titlebar=no')'; ?> <span class="float" style="width: 100px;"><a href="<? echo $brand_edit; ?>"><? echo $auto_increment; ?></a></span> However, something things to go wrong as I'm getting an "Parse error: syntax error, unexpected '=' in ... on line 12" Where am I going wrong with my syntax? What's the correct syntax for having a variable in a select statement? Here's an example of what I'm trying to do (after I'm already connected to the database). Code: [Select] $username = "thomas"; $query = mysql_query( "SELECT * from users WHERE username = $thomas" ); if( mysql_num_rows( $query ) > 0 ) { bla bla... It works if I don't put the WHERE part in, but I get an error if I use it, so I'm assuming I have the wrong syntax for using a variable in the select statement. Hi,
I'm very new to PHP, 2 days in fact, but I've done some programming in other languages. I'm trying to do something pretty basic here. I've inherited a site built on WordPress and I'm trying to override one of the php files contained in a wordpress plugin to do what I want.
I have this line:
<label>
<?php if ( ! $account_required ) echo '<small>' . __( '(optional)', 'wp-jm' ) . '</small>'; ?>
</label>
I understand what the code is doing, if condition is false, then output the HTML <small> tag, I want to add and else condition to the above, that outputs the word "required" in place of where the word optional is. So if $account_required = false then shows the optional in parenthesis as it does now, otherwise I want to show the word "required" in the parenthesis. Super simple, but just can't get the syntax quite right.
Also, can someone explain the double underscore part, specifically this: __( '(optional)', 'wp-jm' ) I understand in PHP periods are used to concatenate, but what is the leading double underscore right before the word "optional" in parenthesis? it's as if there is some function being called or referenced. The end result when the HTML is rendered is "(optional)", but what's up with the leading underscore and the reference to "wp-jm" I assume that there is some plugin or something...
Any help appreciated.
Thanks....
Edited by westside, 11 September 2014 - 05:30 PM. Code: [Select] <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post"> <input type="submit" name="submit" value="Refresh" /> </form> the above works fine for a refresh button ... but does not if I replace <? with <php? Hey all, Let's say I want to do something like this: Code: [Select] <?php function exists($a){ $b ||= $a; } echo exists(1); ?> Basically, every time exists is called, it will only assign b to a if b isn't already initialized. What's the most effective way to achieve the equivalent in php? ternary? Thanks for response. I often see the colon ( : ) being used in syntax however, no amount of searching through my text books or checking php.net reveals to me exactly what this is used for, when it is used and the exact definition of it's value. Intuitively it seems to mean ' or ' but I can't be sure when || is the proper operator for 'or' Can anyone point me towards a url for a succinct explanation ? thanks VJ Quick question, When I run the code below I get an undefined index error for the array. If I define all the indexes I have no problem making it work correctly. I thought writing it like I did below would define the indexes as they are needed. What am I doing wrong? Thanks for looking, $call_data = array(); if($call_segment['did_digits'] == '3300'){ //Check if call was answered if($call_segment['answered'] == 'No'){ $call_data['3300']['abandoned'] ++; } else{ if(in_array($call_segment['finished_on'],$phoneroom_ext)){ $call_data['3300']['phoneroom'] ++; } elseif(in_array($call_segment['finished_on'],$anoka_ext)){ $call_data['3300']['store'] ++; } } } Hi all, new to PHP and had a syntax question. I have the following code: print "<p>{$row['comment_createdate']}; This prints out a date from my sqlquery as a database datetime. I need to format it to display "Monday June 15, 2010 5:15 pm". I'm not sure how/where to attach a date() function to the record. (If it matters, the line above is inside of a loop going through several records). This really applies to attaching functions to columns within a recordset in general. Many thanks ahead of time. I have this variable that I need to get into my database and I just can't think through it. Here is the code. $sql = "INSERT INTO names (id, name, color, uploaddate) VALUE (NULL,'$master[2]['dbid']','$color','$time')"; I know I need to escape those quotes around dbid somehow, but I can't seam to get it figured out. If I have to I will set it = to a different variable, but I don't want to do it that way if I don't have to okay i have table named ZAMJENE with 2 rows only row that i need to setup is named id_zamjena and have values 15 and 16 when i do echo on page it work great but when i press button i get only 16 for both entries full cde is too long so i paste only important parts $query_zamjene = mysql_query ("SELECT * FROM zamjene WHERE id_user_1='$moj_id' AND zamjenjeno='0' ORDER BY id_event_1"); echo "<form method='post' action='event_zamjenjen.php'>"; while ($rows = mysql_fetch_array($query_zamjene)) { $id_zamjena = $rows['id_zamjena']; $id_event_1 = $rows['id_event_1']; $id_event_2 = $rows['id_event_2']; $id_user_2 = $rows['id_user_2']; echo "$id_zamjena"; // THIS ROW WORKS CORRECTLY echo "<input name='id_zamjena' type='hidden' value=$id_zamjena>"; // output of this is always 16 echo "<input name='response' type='submit' value='Prihvati zamjenu' /> <input name='response' type='submit' value='Odbaci zamjenu' /> <br>"; } echo"</form>"; $id = '9'; $MyQuery = "SELECT * FROM bookings WHERE id = '$id'"; $retrieve = mysql_query($MyQuery) or die(mysql_error()); if(mysql_num_rows($retrieve) != 0): $row = mysql_fetch_assoc($retrieve); else: echo 'No Information'; endif; echo 'Full Name: ' . ($row['fullname']) . '<br><br>'; The above code is working for me however when I change it to what I do... $id = ($row['id']); It tells me I have an undefined row variable... What will fix this? Thanks in advance... I have a template page that opens with a GO click from a drop-down in a different page. The variable is being passed through to the URL and in the GET statement. However, my PHP code is producing the following error: Quote Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /data/23/2/100/53/2263053/user/2487001/htdocs/myalaskacenter/events/venues/test_venues-results.php on line 52 . Here is my code: Code: [Select] <?php //Assigns the venueCode tothe variable with a more convenient name $venueURL = $_GET['VenueCode']; @$DB = mysqli_connect('server','username','password','database'); if (mysqli_connect_errno()){ echo '</blockquote><br/><br /> Sorry, this webpage is temporarily unavailable.<br /> <a href="http://alaskapac.centertix.net/">Click here to search for events.</a>'; } else { ?> <?php $Query = "SELECT Events.EventTitle, DATE_FORMAT(Performance.startDateTime, '%W, %M %e, %Y') AS startDate, DATE_FORMAT(Performance.startDateTime, '%h:%i %p') AS startTime, Events.EventID, Events.thumb, Events.ShoWareEventLink, Events.tagline, Performance.category_id, Promoters.Presenter, Promoters.website, Events.startDATE, Events.endDATE, Events.EventOnSaleDate, venues.VenueName FROM ((Events LEFT JOIN Performance ON Events.EventID = Performance.EventID) LEFT JOIN Promoters ON Events.PromoterCode = Promoters.PromoterCode) LEFT JOIN venues ON Performance.VenueCode = venues.VenueCode WHERE venues.VenueCode=".$venueURL." AND Events.group_id=1 AND Performance.category_id!=2 AND Performance.category_id!=5 AND Performance.category_id!=7 AND Performance.category_id!=8 AND Events.EventOnSaleDate IS NOT NULL AND (Performance.PerfType='Public Event' OR Events.EventID='79') AND Performance.endDateTime >= now()-INTERVAL 1 DAY AND Events.PublishDate <= now() AND Events.startDATE IS NOT NULL ORDER BY Performance.startDateTime"; $Result = mysqli_query($DB,$Query); $NumResults = mysqli_num_rows($Result); ?> <?php if($NumResults=0){ echo "<p class='submenu'>$NumResults Performances</p>"; } while ($Row = mysqli_fetch_assoc($Result)){ $eventtitle = $Row['EventTitle']; $eventDate = $Row['startDate']; echo '<p><a href="' . $Row['ShoWareEventLink'] . '"><img src="https://alaskapac.centertix.net/UPLImage/' . $Row['thumb'] . '" alt="' . $Row['EventTitle'] . '" title="' . $Row['EventTitle'] . '" align="left" border="0"><span class="Heading3_blue">' . $Row['EventTitle'] . '</span>'; if($Row['FreeEvents']==TRUE){ echo '<img src="/images/free.gif" alt="Free Event" title="Free Event" width="80" height="80" align="right" border="0"></a><br />'; } elseif ($Row['EventOnSaleDate'] <= date("Y-m-d g:i a")){ /** IF ONSALEDATE<=NOW**/ echo '<img src="/images/logos/ctx/BUY_Tickets_gold.gif" alt="Buy Tickets" title="Buy Tickets" width="85" height="32" align="right" border="0"></a><br />'; } else {/** IF ONSALEDATE!<NOW**/ echo '<img src="/images/logos/ctx/AvailableSoon.png" alt="Available Soon" title="Available Soon" align="right" border="0"></a><br /><i>Tickets available ' . date("l, F j, Y", strtotime($Row['EventOnSaleDate'])) . ' at ' . date("g:i a", strtotime($Row['EventOnSaleDate'])) . '.</i>'; /** +ONSALEDATE **/ } echo '<br />Presented by <a href="' . $Row['website'] .'" target="_blank">' . $Row['Presenter'] . '</a>'; echo '<br />'.$Row['startDate']. ' at ' . $Row['startTime'].' - '.$Row['VenueName']; if ($Row['FreeEvents']==TRUE){ echo '<br /><br />'.$Row['BriefDescription']; } echo '<br /><br /></p><hr>'; } ?> <?php mysqli_free_result($Result); mysqli_close($DB); } ?> Here is my sample Results page: http://www.myalaskacenter.com/events/venues/test_venues-results.php?VenueCode=ACH |