PHP - How Do I Use A Variable With Return Result From Dropdown With Mysql Lookup?
I have found postings close, but not close enough to find my error.
I am looking up data from a MySql table and putting it in a dropdown box on a form. I can select the item, but apparently not really. I am not able to echo it, or post it to a record. I'm sure I am missing something simple, but... Code attached if anyone can show me the errors of my ways. Thank you. Similar TutorialsHello to all. I'm new here and i am very glad to be a part of this community. I am new in PHP/mysql but i try to learn as much as i can in php & mysql. And here is the problem: Into a php or html page i want to display 2 dropdown list to act as a filter for displaying a table. I managed to display a table based on option select from first dropdown but i don'y know how to make or activate the second dropdown list to act as a filter, and when i press "result" to display on the same page the results. Thanks a lot. Hello Everyone, I have a quick question for you all, I think its fairly simple... I have created a database and I am using PHP to grab the data: $usera = $_SESSION['username']; $query2 = "SELECT * FROM tracker WHERE id = '$usera', hidden = yes"; mysql_query($query2) or die('Error, query failed : ' . mysql_error()); This hopefully will return multiple rows which look like this in the database. id username date reps hidden 1 supremebeing 2011-01-02 30 yes 4 supremebeing 2011-04-02 46 yes How would i turn each result into a variable eg: $date1 = 2011-01-02; $date2 = 2011-04-02; $reps1 = 30; $reps2 = 46; I think i have explained that well enough for you to understand, please reply if not though and i will provide more information. Thanks in Advance My login script stores the user's login name as $_SESSION[ 'name'] on login. For some unapparent reason, i'm getting errors stating that $user and $priv are undefined variables, though I've attempted to define $user as being equal to $_SESSION['name'], using $user to look up the the user's privilege level (stored as the su column ) in the SQL table, and then where the result of the sql query is $priv which is then evaluated in an if statement. I can't seem to figure out why this might not be working. The code I'm using: <?php session_start(); function verify() { //verify that the user is logged in via the login page. Session_start has already been called. if (!isset($_SESSION['loggedin'])) { header('Location: /index.html'); exit; } //if user is logged in, we then lookup necessary privleges. $_SESSION['name'] was written with the login name upon login. Privleges // are written in db as a single-digit integer of of 0 for users, 1 for administrators, and 2 for special users. $user === $_SESSION['name']; //Connect to Databse $link = mysqli_connect("127.0.0.1", "database user", "password", "database"); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } //SQL Statement to lookup privlege information. if ($result = mysqli_query($link, "SELECT su FROM accounts WHERE username = $user", MYSQLI_STORE_RESULT)) { //LOOP TO CYCLE THROUGH SQL RESULTS AND STORE Privlege information as vairable $priv. while ($row = $result->fetch_assoc()) { $priv === $row["su"]; } } // close SQL connection. mysqli_close($link); // Verify privleges and take action. Only a privlege of "1" is allowed to view this page. A privlege of "2" indicates special //accounts used in other scripts that have certain indermediate additional functions, but are not trusted administrators. if ($priv !== 1) { echo $_SESSION['name']; echo "you have privlege level of $priv"; echo "<br>"; echo 'Your account does not have the privleges necessary to view this page'; exit; } } verify(); ?>
When I run 'select 1700-price as blah from goldclose as t2 order by dayid desc limit 1' by itself in mysql I get a numerical result: one row, one column. In my php script, the 1700 is actually a variable. so here it is $changequery = sprintf("select $goldprice-price as change from goldclose order by dayid desc limit 1"); $change = mysql_query(changequery); while ($row = mysql_fetch_array($change)) { printf("$row[0]"); } mysql_free_result($changeresult); I get the following error, Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>/root/fuzzy/htmlmain4.php on line 99 Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in <b>/root/fuzzy/htmlmain4.php on line 103 Not sure why? All i want is to get the result of that select statement into a variable such as $change Hello all,
For the UPDATE portion of my CRUD WebApp what I would like to do is to bring in (and display) the values (of a selected row) from my transaction table.
This is working just fine for all fields which are of the "input type". The problem I'm having is with two fields which are of the "select type" i.e. dropdown listboxes.
For those two fields, I would like to bring in all the valid choices from the respective lookup/master tables, but then have the default/selected value be shown based on what's in the transaction table. The way I have it right now, those two fields are showing (and updating the record with) the very first entry's in the two lookup tables/select query.
The attached picture might make things a little bit clearer. You'll notice in the top screenshot that the first row (which is the one I'm selecting to update) has a "Store Name" = "Super Store" and an "Item Description" = "Old Mill Bagels". Now, when I click the "update" botton and I'm taken to the update screen, the values for those two fields default to the very first entries in the SELECT resultset i.e. "Food Basics" and "BD Cheese Strings". Cricled in green (to the top-left of that screenshot) is the result of an echo that I performed, based on the values that are in the transaction record.
I cannot (for the life of me) figure out how to get those values to be used as default/selected values for the two dropdown's...so that if a user does not touch those two dropdown fields, the values in the transaction table will not be changed.
Your help will be greatly appreciated.
Here's a portion of the FORM code:
<form class="form-horizontal" action="update.php?idnumber=<?php echo $idnumber?>" method="post"> <?php // Connect to Store_Name (sn) table to get values for dropdown $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT DISTINCT store_name FROM store_master ORDER BY store_name ASC"; $q_sn = $pdo->prepare($sql); $q_sn->execute(); $count_sn = $q_sn->rowCount(); $result_sn = $q_sn->fetchAll(); Database::disconnect(); // Connect to Item_Description (id) table to get values for dropdown $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT DISTINCT product_name FROM product_master ORDER BY product_name ASC"; $q_id = $pdo->prepare($sql); $q_id->execute(); $count_id = $q_id->rowCount(); $result_id = $q_id->fetchAll(); Database::disconnect(); foreach($fields AS $field => $attr){ $current_store_name = $values['store_name']; $current_item_description = $values['item_description']; //Print the form element for the field. if ($field == 'store_name') { echo $current_store_name; echo '<br />'; echo $current_item_description; echo '<div class="control-group">'; echo "<label class='control-label'>{$attr['label']}: </label>"; echo '<div class="controls">'; //Echo the actual input. If the form is being displayed with errors, we'll have a value to fill in from the user's previous submission. echo '<select class="store-name" name="store_name">'; // echo '<option value="">Please select...</option>'; foreach($result_sn as $row) { echo "<option value='" . $row['store_name'] . "'>{$row['store_name']}</option>"; } // $row['store_name'] = $current_store_name; echo "</select>"; echo '</div>'; echo '</div>'; } elseif ($field == 'item_description') { echo '<div class="control-group">'; echo "<label class='control-label'>{$attr['label']}: </label>"; echo '<div class="controls">'; echo '<select class="item-desc" name="item_description">'; // echo '<option value="">Please select...</option>'; foreach($result_id as $row) { echo "<option alue='" . $row['product_name'] . "'>{$row['product_name']}</option>"; } echo "</select>"; echo '</div>'; echo '</div>'; } else { echo '<div class="control-group">'; echo "<label class='control-label'>{$attr['label']}: </label>"; echo '<div class="controls">'; //Echo the actual input. If the form is being displayed with errors, we'll have a value to fill in from the user's previous submission. echo '<input type="text" name="'.$field.'"' . (isset($values[$field]) ? ' value="'.$values[$field].'"' : '') . ' /></label>'; echo '</div>'; echo '</div>'; }And here's some other declarations/code which I think might be required. $fields = array( 'store_name' => array('label' => 'Store Name', 'error' => 'Please enter a store name'), 'item_description' => array('label' => 'Item Description', 'error' => 'Please enter an item description'), 'qty_pkg' => array('label' => 'Qty / Pkg', 'error' => 'Please indicate whether it\'s Qty or Pkg'), 'pkg_of' => array('label' => 'Pkg. Of', 'error' => 'Please enter the quantity'), 'price' => array('label' => 'Price', 'error' => 'Please enter the price'), 'flyer_page' => array('label' => 'Flyer Page #', 'error' => 'Please enter the flyer page #'), 'limited_time_sale' => array('label' => 'Limited Time Sale', 'error' => 'Please enter the days for limited-time-sale'), 'nos_to_purchase' => array('label' => 'No(s) to Purchase', 'error' => 'Please enter the No. of items to purchase') ); ... ... .... { // If [submit] isn't clicked - and therfore POST array is empty - perform a SELECT query to bring in // existing values from the table and display, to allow for changes to be made $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT * FROM shoplist where idnumber = ?"; $q = $pdo->prepare($sql); $q->execute(array($idnumber)); $values = $q->fetch(PDO::FETCH_ASSOC); if(!$values) { $error = 'Invalid ID provided'; } Database::disconnect(); }If there's anything I've missed please ask and I'll provide. Thanks I am running a search for a specific link on my site in order to make a big change but some of my entries are a little malformed. How do I make this script go to the next record if no match is found. Here are the two pieces of code: $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($result)){ echo $row['name']; echo "<br />"; //After the page is loaded search for specified links for ($i = 0; $i < $hrefs->length; $i++) { $href = $hrefs->item($i); $url = $href->getAttribute('href'); $purl = substr($url, 30,300); //Here I would like to continue the while loop //Maybe if i could find the value "No entities were found" it would escape it just as well? At the end of the code I would like to continue the while loop if i could find the value "No entities were found" on the page that is missing the link I need. Thanks for the help. I am using this code to search my database plus it has a paginate which all works fine. The problem is i have a row count which for some reason counts all records in the database and not just the ones returned from the search query. How to i fix this. Code: [Select] $term = $_GET['term']; $cat = $_GET['cat']; //max display per page $per_page = 4; //get start variable $start = $_GET['start']; // cout records $record_count = mysql_num_rows(mysql_query("SELECT * FROM Table WHERE productname like '%$term%' and category like '%$cat%'")); //count max pages $max_pages = $record_count / $per_page; //may count as decimal if (!$start) $start =0; $sql="SELECT * FROM table WHERE productname like '%$term%' and category like '%$cat%' LIMIT $start, $per_page"; $result = mysql_query($sql); $sql = mysql_query ("SELECT COUNT(*) FROM table"); list($number) = mysql_fetch_row($sql); if (!mysql_num_rows($result)) { die("NO RECORD FOUND") ; exit; } else { echo "Your Search for: <b>$term</b> in <b>$cat</b><br><br>"; } while ($row = mysql_fetch_array($result)){ $num_rows = mysql_num_rows($number); if (!$i++) echo "Total records $number"; ?> <br /> <br /> <?php echo 'ID: '.$row['id']; ?> <br /> <?php echo '<br/> Product Name: '.$row['productname'];?> <br /> <?php echo '<br/> Price: '.$row['price']; ?><br /> <?php echo '<br/> category: '.$row['category']; ?> <br /> <?php } ?> <?php //setup prev and next variables $prev = $start - $per_page; $next = $start + $per_page; // show prev button if(!($start<=0)) echo " <a href='ttr.php?start=$prev'>Prev </a>"; //set var for first page $i=1; for ($x=0;$x<$record_count;$x=$x+$per_page) { if ($start!=$x) echo "<a href='ttr.php?start=$x'>$i</a> "; else echo "<a href='ttr.php?start=$x'><b>$i</b></a> "; $i++; } //show next button if (!($start>=$record_count-$per_page)) echo " <a href='ttr.php?start=$next'>Next</a>"; ?> I am trying to do the following. Except I know that 'return' is not the right method to use, as it stops the script, so what ends up happening is only one row is returned, instead of the three that are there. With return, the data is being passed without being immediately printed, and I end up with the data (but not all of it, because the script stops) in correct place in the page. If I replace return () with echo(), it works fine, in terms of returning the correct data. However, with the way things are setup, if I use echo, the results print at the head of my page. I am using function CreateSideMenu to establish the values for content, and then another function, later on the index.php page, actually creates the page. So what I need is to have something, similar to return (), that passes the information on, but does not immediately print it. Do I make sense? see code below: function CreateSideMenu () { // open CreateSideMenu function include ('/Users/max/Sites/rdbase-llc/hidden/defin/kinnect01.php'); $query = "SELECT content_element_title, content_element_short_text FROM content_main"; $result = mysql_query ($query, $dbc); while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { return ("<p>" . $row[content_element_title] . "</h2>\n<p>" . $row[content_element_short_text] . "</p>"); } Thanks ahead of time. Code: [Select] for ($i = 1; $i<$rows+1; $i++) { $Choicequery ="SELECT PersonA, PersonB FROM modules WHERE GroupID = '$UpdateNumber'"; $Choiceresult = mysql_query($Choicequery); $ChoiceRows = mysql_fetch_array($Choiceresult); $PersonQuery = "SELECT FirstName, LastName FROM Persons p, modules m, users e, group t WHERE m.modID = $ChoiceRows[0] AND e.UserID = m.PersonA AND p.PersonID = e.PersonID"; $PersonResult = mysql_query($PersonQuery); $PersonRows = mysql_fetch_array($PersonResult); $Person2Query = "SELECT FirstName, LastName FROM Persons p, modules m, users e, group t WHERE m.modID = $ChoiceRows[0] AND e.UserID = m.PersonB AND p.PersonID = e.PersonID"; $Person2Result = mysql_query($Person2Query); $Person2Rows = mysql_fetch_array($Person2Result); echo "<Option value = \"$i\">$PersonRows[0] $PersonRows[1] and $Person2Rows[0] $Person2Rows[1] </Option>"; } How do I get it to show the next result when $i increases? All the options are the first people A and B $i number of times. Not sure how to use a loop here to go though the results. Whats the best way? ie $PersonRows[0] $PersonRows[1] are the same for every option friend the code display all the managers name
<?phpand the variable below displays the result $Manager= $row['Manager'] ; but how do i do it on the above dropdown list the it shows which result is in the $Manager variable? This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=331067.0 Undefined variable: return line 38 that line is : echo $return; Below is a look at my full code. Code: [Select] <?php class cms { var $host; var $username; var $password; var $db; function connect() { $con = mysql_connect($this->host, $this->username, $this->password) or die(mysql_error()); mysql_select_db($this->db, $con) or die(mysql_error()); } function get_content($id = ''){ if($id !=""): $id = mysql_real_escape_string($id); $sql = "SELECT * FROM cms_content WHERE id = '$id'"; $return = '<a href="index.php">Go Back?</a>'; else: $sql = "SELECT * FROM cms_content ORDER BY id DESC"; endif; $res = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($res) != 0): while($row = mysql_fetch_assoc($res)) { echo '<h1><a href="index.php?id=' . $row['id'] .'">' . $row['title'] .'</a></h1>'; echo '<p>' . $row['body'] . '</p>'; } else: echo '<p> Sorry! This Page doesn\'t exist!</p>'; endif; echo $return; } }//Ends our class ?> Hey, In my script I am currenlty working on I have 2 classes one which calls the second in the hope it will return a value to it but doesnt send the variable back. The example code below give you and idea of what I am looking for as my script it too long to add. Code: [Select] class oneClass{ function bar(){ $var1 = "test" $two = twoClass(); $result = $two->foo($var1); echo $result; } } class twoClass{ function foo($var1){ $result = $var1 . ' is successful!'; $this->fooTwo($result); } function fooTwo($result){ $result = $result . ' Pass me back now?'; return($result); //Want to pass the variable back to "oneClass->bar();" } } // Starts script $testme = new oneClass(); $testme->bar(); This is a very simple example but states what i am wanting to. Any ideas would be much appreciated! Thanks I'm not versed in PHP OOP and I have some code that I need to echo out onto a page. I don't know what the meaning of $ct->something is in this code. Is this an array of some type? How do I echo out the $ct->title onto another page? Use a function call? I just don't know what all of the $ct variables are and how to get to them. Any help is appreciated. Code: [Select] function current_theme_info() { $themes = get_themes(); $current_theme = get_current_theme(); if ( ! isset( $themes[$current_theme] ) ) { delete_option( 'current_theme' ); $current_theme = get_current_theme(); } $ct->name = $current_theme; $ct->title = $themes[$current_theme]['Title']; $ct->version = $themes[$current_theme]['Version']; $ct->parent_theme = $themes[$current_theme]['Parent Theme']; $ct->template_dir = $themes[$current_theme]['Template Dir']; $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir']; $ct->template = $themes[$current_theme]['Template']; $ct->stylesheet = $themes[$current_theme]['Stylesheet']; $ct->screenshot = $themes[$current_theme]['Screenshot']; $ct->description = $themes[$current_theme]['Description']; $ct->author = $themes[$current_theme]['Author']; $ct->tags = $themes[$current_theme]['Tags']; $ct->theme_root = $themes[$current_theme]['Theme Root']; $ct->theme_root_uri = $themes[$current_theme]['Theme Root URI']; return $ct; } Hello All, I have two php files original.php and return.php retrun.php file returns a variable after I pass $channel_name to it Code: [Select] return $return_variable; I want to assign this return variable to a variable in original.php Something like this Code: [Select] $results = include ('return.php?channel='.$channel_name.'');I am not sure how to do the above code. When I call the return.php from a browser it works properly. Thanks for any help This is object programming right? Is there a performance issue with this? for example: $notfications = ( blah blah ) ? : ''; then if ($notificatiosn != blabla){ echo 'hey'; }or.... $notifications = function(){ do my stuff here then return 'hey'; }Which way is faster or slower? Reason I Ask this is because I've been doing some object orientated programming in javascript, and didn't know you could do it in php. I'd rather do the objective way so I don't have to use so many freaking variables above the regular way, lol. Edited by Monkuar, 22 January 2015 - 12:22 PM. Hello Guys, I have a column named message_status it can only have the values "read" or "unread" in it. I would like to show an image in the column next to it. If the message is "read" then I would like to display a green dot, and if it is unread I would like to display a red dot. I would also like to be able to have anything in the row that's "unread" to appear in bold. I completely stumped by this! I have written the following code, which doesn't seem to work, presumably because it is run after the table has been displayed? I am very new to this so please be gentle! Regards, AJLX $result = mysql_query("SELECT * FROM messages where username ='$username'ORDER BY {$_GET['orderbycol']} $sort"); echo "<table border='1'> <tr width='200'> <th>View</th> // code to display table removed </tr>"; $green_dot = $message_status; $red_dot = $message_status; $green = ""; $red = ""; $bold = ""; while ($row = mysql_fetch_array($result)) { echo "<tr>"; $id = $row['ID']; echo "<td><a href='/view_message.php/?view_message=$id'>View</a></td>"; echo "<td>" .$green . $red."</td>"; echo "<td>" .$bold . $message_status = $row['message_status'] . "</td>"; echo "<td>" .$bold. $row['date_sent'] . "</td>"; echo "<td>" .$bold. $row['contact_name'] . "</td>"; echo "<td>" .$bold. $row['subject'] . "</td>"; echo "</tr>"; } if ($green_dot = 'read'){ $green ='<img src=\"assets/red.jpg\"/>'; echo $green; } else { $red ='<img src=\"assets/red.jpg\"/>'; $bold = "<b>"; echo $red; Hello, So I have a content management site set up, but I'm stuck on one part. I have a query. Code: [Select] Select `email` FROM author WHERE author.id IN(SELECT authorid FROM job WHERE id = '$_POST[id]') I'm a beginner in PHP and SQL. Basically I need the query to run, it will come out with one result and I need that to be where the email is sent to. This is the existing code I have for sending out the email $subject = " Job Application Confirmation"; $message = "Hello $_POST[name] , \r\rYou, or someone using your email address, has applied for the job: $text Using the Resource Locator at Prahan.com. Keep this as future reference. \r\r Full Name: $_POST[name] \r Location: $_POST[location] \r Email: $_POST[email] \r Additional Information: $_POST[info] \r Job ID: $id \r Job Name: $text \r \r Expect a response shortly. \r\r Regards, Prahan.com Team"; $headers = 'From: Prahan.com Team <noreply@prahan.com>'; 'Reply-To: noreply@prahan.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $to1 = 'pratik@prahan.com'; mail($to1, $result, $message, $headers); Thanks in Advance! I think I might have already asked something similar, but... my code has: $ip = gethostbyaddr($_SERVER['REMOTE_ADDR']); $host = $_SERVER['HTTP_HOST']; my field header for "$host" is "VISITOR DOMAIN ADDRESS". I'm not sure what I was thinking. That's not possible to capture is it? Last I read, and I think someone here told me, it is only possible to capture the IP and server name of the requesting computer? the var $ip in my report, for instance, returns: 173-28-199-198.client.mchsi.com if I visit the page, and that is the name of the server assigned to my ISP. on PHP's doc page, there are the vars REMOTE_HOST and REMOTE_USER and I haven't tried those. Their example does not list any return value for those vars. what do they return? Edited November 23, 2019 by ajetrumpetI want to save the results of a loop as a variable ie $output. I have tried encasing the php within quotes but it does not work. Is there a way to save the complete results as a variable? $result = mysql_query("SELECT * FROM $table2 WHERE $db_item_1 OR $db_item_2", $connection); if (!mysql_num_rows($result)) { echo "Error 13424 - not working"; exit(); } while ($row = mysql_fetch_array($result)) { echo "<tr><td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\" style=\"font-size: 20px;\">" . $row['date'] . "</div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\"></div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\" style=\"font-size: 20px;\">" . $row['title'] . "</div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\"></div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\" style=\"font-size: 20px;\">" . $row['cost'] . "</div></td> </tr>"; }echo $complete;() The part I want as one result (ie. $complete) is the result of the while loop. There is always at least one result but sometimes 10 which means that it creates 10 table rows. I need to do it this way as later on in the page I use a pdf converter which does not allow loop checks within it otherwise I would just place it within the converter. |