I have made a dropdown box that is filled by a query that looks for company names from company name database, these names also have and ID number that I don't want displayed but are looked up in the query. I need the ID number to link to sites of the company so somehow when I hit the submit button on the site page it finds the ID number by looking at the position value and relating that to the position on the query array I just don't know what to do. If it helps this is how I fill the dropbox:
mysql_select_db("DB", $con);
$query = "SELECT Company_Name, ID FROM company_table";
$result = mysql_query($query) or die(mysql_error());
$options ='';
$num = 0;
while ($row=mysql_fetch_array($result)) {
$num = $num+1;
$options.= "<OPTION VALUE=\"$num\">".$row["Company_Name"];
}
<SELECT NAME=thing>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
Any Ideas?
There are two immediate ways this can be done. One is to keep it the way you have it using an index, $num; the other way is to use the actual company id field, ID. If you stick with the index of $num, when the user submits the form (i.e. - selects a company), you will have to re-query the database and re-loop through the results to find the specific company (or you could use a LIMIT/OFFSET; notes at end of answer).
I would recommend using the actual company id in your form:
while (($row = mysql_fetch_assoc($result))) {
$options.= '<option value="' . $row['ID'] . '">' . $row["Company_Name"] . '</option>';
}
This will generate a list of options, like you currently have, except the value of each will be the specific company id. When the user submits the form, let's assume the form is using POST, you can get the ID with:
$companyId = (isset($_POST['thing']) && is_numeric($_POST['thing'])) ? intval($_POST['thing']) : false;
$results = mysql_query('SELECT * FROM company_table WHERE ID=' . $companyId);
.. and then process as you desire.
I use $_POST['thing'] in the above example as that is what your code-example has the select field named. Also, I make the assumption that ID is an integer.
If the actual ID needs to remain hidden, as specified, the index of $num can be used with MySQL's LIMIT/OFFSET as follows:
$selectedCompany = (isset($_POST['thing']) && is_numeric($_POST['thing'])) ? intval($_POST['thing']) : -1;
if ($selectedCompany >= 0) {
$query = "SELECT Company_Name, ID FROM company_table LIMIT " . $selectedCompany . ", 1";
// process as desired
}
An option is to add a "created" field to the company table that is a timestamp, or just a 2nd column that is a random UUID column. Then set the value of the dropdown to this column so you don't show ID but you will still know the record since you are using the "other" id as well.
I actually use this method in one of my programs where it was the same situation as you, the client didn't want the ID to be shown.
If you don't want to go with this method (because you don't want a 2nd column) you could just md5 hash the ID or some other hashing method.
Then you would do
SELECT * FROM company where md5(id) = "$value".
The downside to this method is that it is an expensive query, since you won't be using an index and it has to compute all the md5 hashes for each id.
Related
Basically, I want to take a value from running a stored procedure that randomly generates a number, and use it later on in the website. Eventually, I'm going to need to pass that randomly generated number back to the MySQL database depending upon the actions that the user takes.
Stored Procedure:
BEGIN
SET #leftplayerone = 0;
SET #rightplayerone = 0;
SET #leftplayerone = (SELECT FLOOR(RAND()*((SELECT COUNT(*) FROM
Players)-1+1))+1);
WHILE #rightplayerone = 0 OR #rightplayerone = #leftplayerone
DO
SET #rightplayerone = (SELECT FLOOR(RAND()*((SELECT COUNT(*) FROM
Players)-1+1))+1);
END WHILE;
SELECT #leftplayerone;
SELECT #rightplayerone;
END
I have a separate table that includes a number of players. I want to randomly pull 1 player from that table and then display that player on my website. Then, I want to randomly display a different player from that same table. The user should then be presented with these two randomly generated players and then choose an option presented to them with 5 different buttons. I want to then send that response, along with the two players that were randomly generated back to the database to store that information.
I'm just looking for some help on how to pull the two randomly generated players from the stored proc and display that on the site - I just put the rest of the details for context.
Update:
My PHP code is:
<?php
$sql = "CALL FantasyUnited.GetRandomPlayersForTradeProposal();";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row["PlayerOne"] ."</td><td>". $row["PlayerTwo"] ."
</td></tr>";
}
echo "</table>";
}
else {
echo "0 result";
}
$conn-> close();
?>
I am now able to display the random Player IDs - now I need to figure out how to display the player's name that correlates to the player ID instead of just displaying the ID number. Then save that information and pass it back to the database when a user clicks on a button regarding those two players.
http://pr0digy.me/trades.php
The user will select one of the options (buttons) below the names of the players. I want the button they pushed and the names of the players stored and sent back to the database.
Change the last line of the procedure to:
SELECT #leftplayerone AS leftplayer, #rightplayerone AS rightplayer;
so that you can fetch both results at once in PHP.
Then in PHP you can do:
$result = $pdo->query("CALL yourProcedure");
$row = $result->fetch(PDO::FETCH_ASSOC);
$leftplayer = $row['leftplayer'];
$rightplayer = $row['rightplayer'];
This is PDO syntax, the corresponding mysqli syntax is not very different.
I have any information stored in a database which is picked up and displayed with radio buttons. I like to display information from the database based on what radio buttons the user has chosen. For example I have a list of activities a user may have done and based on what they have chosen I would like to display other activities they could do. I can get the system to display random information from the database using RAND(). Can't find any online tutorials for this.
Please give us more information or a concrete example of your problem, all i can tell you is that your SQL request in your second code snippet will probably not give the expected result :
SELECT * FROM activities ORDER BY RAND() LIMIT 1
You probably don't want to ORDER BY RAND() (may be impossible) nor LIMIT 1, you just want to pickup one random row from your mysql results, am i right ?
If i am right just get the full resultset (with no order by / no limit clause), generate a random with php (between 0 and resultset size) the pick the expected row from resultset.
Ok, so i don't know your database structure, but lets say you have a table for activities and table for the activities the user does. For the sake of this example we will call them activities and activities_by_user
The activities table will have columns
activity_id | activity
The activities_by_user will have columns
activity_id | user_id
So your display code will look something like this
$query = "SELECT activities.*, activities_by_user.activity_id AS has_activity FROM activities LEFT JOIN activities_by_user ON activities_by_user.activity_id = activities.activity_id AND user_id = 1 ORDER BY RAND()";
// The user_id in just for example. There should be the id of the logged user
$result = mysqli_query($con, $query) or die('Error');
while($row = mysqli_fetch_object($result)) {
// If the has_activity field is not null, then the user does that activity
$checked = (isset($row->has_activity) && $row->has_activity != null) ? 'checked' : '';
echo '<label><input type="checkbox" name="activities[]" value="' . $row->activity_id . '" ' . $checked . ' />' . $row->activity . '</label>';
}
This will generate checkboxes for all the activities and will check does who are done by the user.
i try something like this :
function userrank($userid){
$sql = mysql_query("SELECT * FROM users ORDER BY atacs DESC");
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
if ($row['username'] == $userid) {
echo 'You are on ' . $i . ' in the general leaderbord';
}
}
}
On the leaderboard it shows me the rank correctly, but i want to show me on another page too , on the "youraccount" page , for this i try to make this function.
what is wrong ?
Basically what you're doing here is counting how many users have an atacs greater than or equal to $userid's atacs. Problems with this:
Terribly inefficient. Note the database retrieves and sends to your
while loop an entry for every user, even those who have an atacs
less than the $userid. All but one of these while loop iterations
does nothing by design. Lots of wasted time sending data from the
database to PHP, which doesn't even use it.
Pulls way more data back
than is necessary. You end up with every row for every user in
your entire users table - but your result is just a scalar number
( how many users with > score ).
Actually gives you wrong results
in the case that your score is tied with others'. In this case some
users with the same score may be counted as "above" the user, others
as "below the users".
Databases are good at iterating over data; it's
all "locally" accessible and the database engine can make many
optimizations if you can describe in SQL what you are trying to
accomplish. So instead of doing it that way, why not just do
everything in the database?
set #user_atacs = ( select atacs from users where id = 12 );
select count(*) +1 from users where atacs > #user_atacs;
I've mocked up the table here: http://sqlfiddle.com/#!2/ff9a86/3
This solution essentially just counts the number of users with a higher atacs than the current user. All users with the same score will get the same rank, and the next rank will be appropriately higher, so it doesn't suffer from any of your method's errors.
As a final note, the most appropriate way to do something like leaderboards is probably to precompute the leaderboard periodically and then use the results to show each user's position in the leaderboards, rather than trying to compute it on the fly for each user. But that's even farther out of scope :)
You have to increment $i. I'm Assuming that the leader board order is represented by the result of your query. So, if true, change your code as follows:
function userrank($userid){
$sql = mysql_query("SELECT * FROM users ORDER BY atacs DESC");
$i =0; // starts out with an unknown rank.
while ($row = mysql_fetch_assoc($sql)) {
$i++; // increment $i here.
if ($row['username'] == $userid) {
echo 'You are on ' . $i . ' in the general leaderbord';
}
}
}
The $i will increment for sure. So, if it is not working still, I'd look to see what the result of your query is. Try echoing $row['username'] and see what the value is and then compare that to the echoed calue of $userid.
I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.
To give some context, the following dropdown is within a form that gives the current profile description of an animal stored in the database: i.e, this pony is yea high, of this gender, owned by somesuch, etc. The purpose of the form is to edit these current values. There are various options that can be overwitten freely, others where I want the choice limited to options from a dropdown menu.
The following is the current code I am using for the Gender field, which - although it does work - cannot be the proper way of doing things. I would be more interested in a method that queried the current state, gave the current state as the default option, stored the current state, queried other available states not equal to the stored current state, then gave the remaining states as options. It is that method that I could best adapt to all the other dropdowns on the form.
There are two tables referenced - the profile tbl and the prm_breedgender tbl. Each gender is given an ID, each profile is then given a corresponding ID to signify their gender (male=1, female=2, etc.). The $profile variable is that which signifies the current profile being looked at.
<label for="profile-gender">Gender / Type:</label>
<select name="profile-gender">
<?php
$genderresult = mysql_query("SELECT prm_breedgender.BreedGender
FROM profiles, prm_breedgender
WHERE ProfileID = $profile
AND prm_breedgender.BreedGenderID = profiles.ProfileGenderID");
$row = mysql_fetch_array($genderresult);
echo '<option value="' . $row['BreedGenderID'] . '">' . $row[BreedGender] . '</option>';
$exgenderresult = mysql_query("SELECT prm_breedgender.BreedGender
FROM profiles, prm_breedgender
WHERE ProfileID = $profile
AND prm_breedgender.BreedGenderID != profiles.ProfileGenderID");
while ($row = mysql_fetch_array($exgenderresult)) {
echo '<option value="' . $row['BreedGenderID'] . '">' . $row[BreedGender] . '</option>';
}
?>
</select>
Any help would be greatly appreciated. I'm not all that experience (obviously!) so accompanying explainations would be fantastic.
You can combine it into a single query, using a computed 'order by' value:
SELECT ...
FROM ...
WHERE ...
ORDER BY (prm_breedgender.BreedGenderID = profiles.ProfileGenderID) DESC
The order by clause will evaluate to either true (you're on the record that should be first) or false (any other record), which gets cased to a value 1/0 which can be sorted, and by doing it in decreasing order, the true values (1) come out first.