PHP - Mysql Select Problem W/php
I'm working on my website, and I'm having a bit of trouble in getting PHP to select the proper data.
I'm trying to select usernames from my database where rank is equal to one (the highest, in my system). As such, I attempted this code; Code: [Select] // Connection info above this line... mysql_select_db("users"); $query = mysql_query ("SELECT displayname FROM login WHERE rank = 1"); $query_a = mysql_fetch_array($query); var_dump($query_a); The var_dump resulting from that is as follows; Code: [Select] array 0 => string 'Seltzer' (length=7) 'displayname' => string 'Seltzer' (length=7) Everything is working correctly, except for the fact that my database contains two displayname rows where rank is equal to one (EDIT: Two distinct rows). In fact, I can run a search of it in phpMyAdmin and get the two that my PHP code should be returning. phpMyAdmin generated the following query, which Inserted into my code in order to double-check things; Code: [Select] SELECT `displayname` FROM `login` WHERE `rank` =1 LIMIT 0 , 30 Even after I swapped my queries, the PHP code still returned the same var_dump as above. Complicating things further, I've noticed another function I've made, which queries "SELECT rank WHERE displayname = '$displayname'", functions perfectly. I've gotten rid of pretty much any source of the error I could think of; I'm testing the function on an otherwise empty page, I've removed any classes being used, and I've tried about a million different queries. Can someone help me out with this? I'm being held up by it and I'm sure that this is a simple fix. Thanks in advance, Dustin Similar TutorialsThis is a continuation of a previous post. I am trying to get the names of countries that are in a database table. It's not working! All I get is a Submit button, but no data. This is what I understand from the code that Psycho suggested: I am unfamiliar with the function and the use of the FOREACH constuct. looking at the PHP manual there are two syntaxes. It appears that Psyhco has used the second form where the current element's key is assigned to $key variable for each itteration. foreach (array_expression as $key => $value The 2 variables he used are $id and $label I assume that the line: $optionsHTML = ''; is the array built from the expression: $optionsHTML .= "{$label}\n"; Because I was not familiar with the PDO method, but have used mysqli, I had to rewrite the data retrival part which I believe is OK. I guess that the line : $countryOptions = buildSelectOptions($countries); is used in conjunction with the function to build the array. The HTML part that Psycho wrote puts the variable into the Form format for a selection list. Why is the $optionsHTML also inclosed in the option tags? Have I got the HTML part correct or is it the data extraction part that is incorrect? Here is the code: <? include("AddStats_admin_connect.php"); //connect to database doDB(); //Function to build select options based on passed array function buildSelectOptions($options) { $optionsHTML = ''; foreach($options as $id => $label) { $optionsHTML .= "<option value='{$id}'>{$label}</option>\n"; } return $optionsHTML; } //Run query to get the ID and Name from the table //Then populate into an array $clist_sql = "SELECT CID, Country FROM Countries"; $clist_res= mysqli_query($mysqli, $clist_sql) or die(mysqli_error($mysqli)); if (mysqli_num_rows($clist_res) < 1) { //this Country not exist $display_block = "<p><em>You have selected an invalid Country.<br/> Please try again.</em></p>"; } $countries = array(); while($Ctry_info = mysqli_fetch_array($clist_res)) { $countries[$Ctry_info['CID'] = $Ctry_info['Country']]; } $countryOptions = buildSelectOptions($countries); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Stats</title> <link rel="stylesheet" href="stylesheets/style.css" /> <!--[if IE]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <? echo $countryOptions; ?> </br></br></br></br></br></br></br></br> <!Later in the HTML for the page <form action="Ctrystats.php" method="post"> <option name="country" value=<? echo $countryOptions;?>Country</option></br></br> <input type="submit" value="Submit Choice"> </form></p> </body> </html>I think I am nearly there so I would appreciate some help to finish this coding. Note: If you make your questions easy to read, then you have better chances of a quality answer. Use [ code ] ] tags. 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 Hello, For some reason the following query returns 0 rows: $query = mysql_query(" SELECT * FROM `businesses_touchlocal_temp` WHERE `postcode` = '".$this_business['postcode']."' LIMIT 1 ")or die(mysql_error()); echo mysql_num_rows($query); echo "<br />"; var_dump($this_business['postcode']); Quote 0 string( "SE8 5" But this returns 1 row: $query = mysql_query(" SELECT * FROM `businesses_touchlocal_temp` WHERE `postcode` = 'SE8 5' LIMIT 1 ")or die(mysql_error()); echo mysql_num_rows($query); Quote 1 Kind of banging my head here. Thanks! Basically, is this a good idea to use, or rather select only the fields you need for a certain reason. Say I have the fields: uid,uname,upass,usalt, and udisplayname. If a sneaky little .... somehow injected a query that is used for users that are logged in, wouldn't it be better to only have the relevant fields selected? ( In this case, uname,upass,and usalt should only be touched if adding a user, or having a user log in, because beyond that, why would you need something that's purpose is only for authenticating a user? ), or rather select all fields?. I've been wondering this for a while. So if I used my method ( select only relevant fields ), even if a sneaky little .... did inject sql to try and get a certain user's login information, it would not give them that info because those fields are NOT selected, as opposed to selecting all fields, and having that sneaky little .... get ahold of that users info.. Still even if I used uname and upass, they'd still have to figure out that I'm using a unique salt for each user, and that even if 2 users have the same password, theyd need to do seperate rainbow tables for each password. I have a table with a field called "tags" and below is an example of how this field might look like. pensions, employee benefits, group benefits, defined contribution, auto-enrollment I want to perform a query to get this field for all of the rows in my table. However is there a way to stop mysql from returning duplicates. For example if another field read, pensions, employee benefits, group benefits, defined contribution, auto-enrollment, tax Then it would only return "tax" from this field as it's already return pensions, employee benefits etc. Thanks for any help. I need to select all fields from two tables and echo that data. Fields are the same in both tables but has different data. <?PHP include "dbconnect.php"; function pretvoriDatum($mysqlDatum) { $tmp=explode("-", $mysqlDatum); $datum=$tmp[2] . "." . $tmp[1] . "." . $tmp[0]; return $datum; } $sql="SELECT * FROM novosti A, dogadanja B"; if (!$q=mysql_query($sql)) { echo "Error" . mysql_query(); die(); } if (mysql_num_rows($q)==0) { echo "No data</div>"; } else { ?> <?PHP while ($redak=mysql_fetch_array($q)) { ?> <?php echo $redak["a.naslov"]; ?> <?PHP echo $redak["a.slika"]; ?> <?php echo $redak["b.tekst"]; ?> <?php echo $redak["a.objavio"]; ?> <?PHP echo pretvoriDatum($redak["b.datum"])?> <?PHP } } ?> Please help, I don't know how to do that I have a MySQL database. The table name is prodcat - it has 3 fields sku, category and codes. Some of the categorys have multiple items in it which is seperated by /
for example: Ceramics/Sale Items or just Ceramics
in the codes it looks like this: ceramics,saleitems or just ceramics
Basically i want to loop through each sku in the prodcat table and every sku that is in ceramics I want it to echo an image. And if that sku is in multiple categories it needs to show the image no matter what category you are in. So if it is a ceramic item that is also on sale I want the image to appear in both those categories
I've tried this multiple ways and can get a partial result but can not get it completely the way I want it. Basically I can get it to give me the result in one category but it won't give me the result in both categories.
Thanks for the help.
Hi guys I have a two tables in my mysql branch: id branchname postcode then a user table id username password branch1 branch2 so far I have a select form as below which populates the select form from mysql branch 1<select name='branch1'><p /> <?php $branchdropdown=mysql_query("SELECT id ,branchname, postcode FROM branch"); while($row = mysql_fetch_array($branchdropdown)) { // echo '<option value="' .$row['stationname']. '"></option>' ; echo "<option value=\"".$row['id']."\">".$row['branchname']."\n "; $postcodeone=$row['postcode']; } ?> and then this will be inserted in mysql as below $submit = mysql_query("INSERT INTO users (branch1, branch2) VALUES ($postcodeone, $postcodetwo)"); echo "This entry has been added to our database"; </select> but it only inserts the branch id and not the password, can you please tell me what im doing wrong? What is this a. b. c. before the fields? I'm not understanding it. I know is about foreign key and reference, but why a. b. c. ?? Code: [Select] <?php $user_id='1'; // User table user_id value $update_sql=mysql_query("SELECT a.username, a.email, b.update_id, b.update, b.time, b.vote_up, b.vote_down FROM users a, updates b, friends c WHERE b.user_id_fk = a.user_id AND c.friend_one = '$user_id' AND b.user_id_fk = c.friend_two ORDER BY b.update_id DESC LIMIT 15"); while($row=mysql_fetch_array($update_sql)) { $username=$row['username']; $email=$row['email']; $update_id=$row['update_id']; $update=$row['update']; $time=$row['time']; $up=$row['vote_up']; $down=$row['vote_down']; //Avatar $lowercase = strtolower($email); $image = md5($lowercase); $avatar ='http://www.gravatar.com/avatar.php?gravatar_id='.$image; //Update HTML tags filter $htmldata = array ("<", ">"); $htmlreplace = array ("<",">"); $final_update = str_replace($htmldata, $htmlreplace, $update); // Updates Results Display here } ?> I have the following sql which works fine "SELECT AVG(ratings.score), articles.* FROM ratings, articles where ratings.article_number = articles.article_number group by article_number" However I want to add to this statement to make sure that it only returns the results where the field avg(ratings.score) is between 3 and 4. I tried the sql below but it came up with the error "invalid use of group function". SELECT AVG(ratings.score), articles.* FROM ratings, articles where ratings.article_number = articles.article_number and AVG(ratings.score) < 4 group by article_number Thanks for any help This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=350716.0 hello with tis button i generate some statistics from mysql if(isset($_POST['sub1'])) { $result = mysql_query("SELECT servitoros1, COUNT(*) from history WHERE serv LIKE '%be%' group by serv1"); while($row = mysql_fetch_row($result)) { echo "<tr>"; foreach($row as $cell) echo "<td ALIGN=\"center\">$cell<FONT></td>"; echo "</tr>\n"; } mysql_free_result($result); } but each record have datetime field!! so how can i set this display betwean 2 selectable datetimes e.g. from 2/2/2011 15:45 to 3/2/2011 23:59 guys, please help i need balance amount of fees all students has to pay. Following is the DB structure. `feepayid` is primary key for paymentstable and paymentregister & `studentid` is primary in studentstable. I have written a query for this, please evaluate the query. paymentstable feepayid classid paydate paymode feeamount remarks feediscount 32 8 2012-03-06 19:32:35 1 500 hgfhf 0 31 8 2012-03-04 19:32:35 1 800 hgfhf 0 30 8 2012-02-06 19:32:35 1 1200 hgfhf 0 29 8 2012-02-06 19:32:35 1 1100 hgfhf 0 paymentregister feepayid payid totalfee studentid 32 3 1500 2 31 2 3500 2 30 1 4500 4 29 3 5500 4 studentstable studentid studentname 2 john 4 mathew 5 peter 6 mary Code: [Select] SELECT d.`studentid`, SUM(a.`totalfee` - (SELECT SUM(`feeamount`) FROM `paymentstable` WHERE a.`feepayid` = `feepayid`)) AS balancefee FROM `studentstable` d LEFT JOIN `paymentregister` a ON a.`studentid` = d.`studentid` GROUP BY d.`studentid`; I'm experimenting out premade codes and trying to make them some how work the way I want to. This is "my" image uploader. For the uploader is suppose to find the image AND the code stored in mysql, but it doesn't seem to find it. any problem? <?php $link = mysql_connect("localhost", "mcd", "whatanicepassword"); mysql_select_db("mcd", $link); if (!isset($_POST["code"])) { die ("Error: Not all fields complete"); } $limit_size=5120; $target = "skin/"; $target = $target . basename( $_FILES['uploaded']['name']); $ok=1; $filelol = $_FILES['uploaded']['name']; $file_size=$_FILES['uploaded']['size']; $filecheck = "skin/".$filelol; //This is our size condition if ($file_size >= $limit_size) { echo "Your file is too large.<br>"; $ok=0; } if (file_exists($filecheck)) { } else {echo $filelol." does not exist in the database. Please upload at the main site.<br>"; $ok=0;} // username and password sent from Form $uploaded=mysql_real_escape_string($_POST['uploaded']); $code=mysql_real_escape_string($_POST['code']); $checkquery = mysql_query("SELECT * FROM user_list WHERE uploaded = '$uploaded' AND code = '$code'") or die("Error : " . mysql_error()); $num_rows=mysql_num_rows($checkquery); if ($num_rows < 1 ) { echo 'File not found in MySQL<br><br><br>'; $ok=0; } else {echo 'YES!';} //This is our limit file type condition if (($_FILES["uploaded"]["type"] != "image/png")) { echo "You may only upload PNG files.<br>"; $ok=0; } if ($ok==0) { Echo "Sorry your file was not uploaded<br>"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ".$filelol." has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } ?> Hey guys I want to create a class containing a SELECT statment in order to make in re-usable though out my entire applicion. Any one no a good way to go about this? This is the native way i have done it. I want to be able to make this into a class becuase i have more than one database with the same tables. Code: [Select] $articles = "SELECT * FROM blog_posts INNER JOIN users ON blog_posts.aurthor_id=users.user_id INNER JOIN post_categories ON blog_posts.category_id=post_categories.id"; $articles_results = mysql_query($articles)or die(mysql_error());; $var = @$_GET['q'] ; $trimmed = trim($var); $table = @$_GET['field']; $query="SELECT * FROM contacts WHERE @'table' contains @'trimmed' order by id"; $result=mysql_query($query); $num=mysql_numrows($result); Why wont this work? Zacron i want to make a monthly report the user selects month from drop down and i must get the specified dates of that month from the DB I am using ajax to get the dates Hi Guys I don't know if this is possible but can someone point me in the right direction. I have a php function which takes two inputs and returns an output. for simplicity's sake let's say it's an addition function. What I want to do is use a mysql select statement to show all the rows from a database where field1 and field2 equal '3'. Here's the sort of thing I mean. function addNumbers($one,$two) { return $one + $two; } mysql_query("SELECT * FROM table WHERE 'addNumbers(field1,field2)' = '3'"); What I actually want to do is a lot more complex than this but I am trying to understand how to make the syntax work in simple terms first. Can anybody help? Many Thanks Dan How can i select the last 3 rows in a table and order it by ASC. When i use DESC it displays the results in the wrong order. $query24 = mysql_query("SELECT * FROM notifications WHERE to_id='$session' AND state='1' ORDER BY id DESC LIMIT 3 "); This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=348309.0 |