I am trying to update 11 rows at a time - cricket team (11 players) posted from a form page before, and then I want to update the first table called with these players. (The table includes player, order and team.)
<?php
session_start();
// Edit this to connect to your database with your username and password
$db_name="a1467234_cricket"; // Database name
$tbl_name="statistics"; // Table name
// Connect to server and select databse.
$conn = mysql_connect("mysql17.000webhost.com","*******","*******") or die(mysql_error());
mysql_select_db("$db_name")or die("cannot select DB");
$one = $_POST["one"];
$two = $_POST["two"];
$three = $_POST["three"];
$four = $_POST["four"];
$five = $_POST["five"];
$six = $_POST["six"];
$seven = $_POST["seven"];
$eight = $_POST["eight"];
$nine = $_POST["nine"];
$ten = $_POST["ten"];
$eleven = $_POST["eleven"];
$team = $_POST["team"];
$sql = "UPDATE first
SET player = (CASE
WHEN order = 1 ='$team' THEN '$one'
WHEN order = 2 AND team ='$team' THEN '$two'
WHEN order = 3 AND team ='$team' THEN '$three'
WHEN order = 4 AND team ='$team' THEN '$four'
WHEN order = 5 AND team ='$team' THEN '$five'
WHEN order = 6 AND team ='$team' THEN '$six'
WHEN order = 7 AND team ='$team' THEN '$seven'
WHEN order = 8 AND team ='$team' THEN '$eight'
WHEN order = 9 AND team ='$team' THEN '$nine'
WHEN order = 10 AND team ='$team' THEN '$ten'
WHEN order = 11 AND team ='$team' THEN '$eleven'
ELSE player
END
WHERE order IN (1,2,3,4,5,6,7,8,9,10,11))";
echo "Updated team selection";
mysql_close($conn);
?>
Does anyone know how to get the update script working please? No errors are displayed, and it just doesn't change the database.
You need a mysql_query($sql); to execute your query on the database
Using for loop might be easier, neat and smarter way for your query. This might be little helpful for you:
<?php
for($i=1;$i<$count;$i++) {
$updatesql="update first set player ='".$_POST['player_'.$i]"' where team ='".$_POST['team_'.$i]"' ";
mysql_query($updatesql);
}
?>
You might need slight modification with this one.
for eg. you need to post data in this way:
player_1, player_2 etc. and team in team_1, team_2 etc.
bviously, you are missing a closing parenthesis ')' after the END.
By the way, the first case condition (order = 1 ='$team') doesn't seem to make any sense.
Anyway, the query below should work. Please note that the . . . would need to be populated in the same pattern as the first and second players.
$sql = "
UPDATE first a,
(
SELECT 1 AS `order`, '{$one}' AS player, '{$team}' AS team
UNION ALL
SELECT 2 AS `order`, '{$two}' AS player, '{$team}' AS team
.
.
.
UNION ALL
SELECT 11 AS `order`, '{$eleven}' AS player, '{$team}' AS team
) b
SET a.player = b.player
WHERE a.`order` = b.`order`
AND a.team = b.teamenter
";
Related
WRT: how to insert records for top 10 enteries only
This is more refined question.
I have gathered top 10 users for specific task. Using the query given below.
mysql_query("SELECT `userid`, SUM(`points`) as `total` FROM
`tablename` GROUP BY `userid` ORDER BY total DESC LIMIT 10");
Now , I need to award bonues to the top 3 gathered users only, out of these selected top 10. I am not getting the idea , on how to write query for this purpose.
The top 3 bonuses are different for top 3
1: First user gets 1000 points
2: 2nd user gets 500 points
3: 3rd user gets 100 points
I need to update one field in tablename = user , field name = points.
To update the bonus i am using the below query(general query):
$Db1->query('UPDATE user SET points=points+'.$rate.'
WHERE userid = '.$credituser);
I hope this question is well elaborated as per the community standards.
Kindly guide.
Working on a pure MySQL version.
As you've PHP tagged, I'll incorporate that into my answer :)
(Ps: Don't use mysql_*. As OP used mysql_*, my answer will)
Fetch the results
Loop through the results
Update the results depending on their position
$objGet = mysql_query("SELECT `userid`, SUM(`points`) as `total` FROM
`tablename` GROUP BY `userid` ORDER BY total DESC LIMIT 10");
if( mysql_num_rows($objGet) ) {
$intIteration = 1;
while( $arrResults = mysql_fetch_assoc($objGet) ) {
switch($intIteration) {
case 1 :
mysql_query("UPDATE tablename SET points = points + 1000 WHERE userid = ". $arrResults['userid']);
break;
case 2 :
mysql_query("UPDATE tablename SET points = points + 500 WHERE userid = ". $arrResults['userid']);
break;
case 3 :
mysql_query("UPDATE tablename SET points = points + 100 WHERE userid = ". $arrResults['userid']);
break;
default:
//No idea.
//Not in the top 3.
break;
}
$intIteration++;
}
} else {
//No users.
}
I got a little problem, I've got a database, in that database are different names, id, and coins. I want to show people their rank, so your rank has to be 1 if you have the most coins, and 78172 as example when your number 78172 with coins.
I know I can do something like this:
SELECT `naam` , `coins`
FROM `gebruikers`
ORDER BY `coins` DESC
But how can I get the rank you are, in PHP :S ?
You can use a loop and a counter. The first row from MySql is going the first rank,I.e first in the list.
I presume you want something like:
1st - John Doe
2nd - Jane Doe
..
..
right?
See: http://www.if-not-true-then-false.com/2010/php-1st-2nd-3rd-4th-5th-6th-php-add-ordinal-number-suffix
Helped me a while ago.
You could use a new varariable
$i = "1";
pe care o poti folosi in structura ta foreach,while,for,repeat si o incrementezi mereu.
and you use it in structures like foreach,while,for,repeat and increment it
$i++;
this is the simplest way
No code samples above... so here it is in PHP
// Your SQL query above, with limits, in this case it starts from the 11th ranking (0 is the starting index) up to the 20th
$start = 10; // 0-based index
$page_size = 10;
$stmt = $pdo->query("SELECT `naam` , `coins` FROM `gebruikers` ORDER BY `coins` DESC LIMIT {$start}, {$page_size}");
$data = $stmt->fetchAll();
// In your template or whatever you use to output
foreach ($data as $rank => $row) {
// array index is 0-based, so add 1 and where you wanted to started to get rank
echo ($rank + 1 + $start) . ": {$row['naam']}<br />";
}
Note: I'm too lazy to put in a prepared statement, but please look it up and use prepared statements.
If you have a session table, you would pull the records from that, then use those values to get the coin values, and sort descending.
If we assume your Session table is sessions(session_id int not null auto_increment, user_id int not null, session_time,...) and we assume that only users who are logged in would have a session value, then your SQL would look something like this: (Note:I am assuming that you also have a user_id column on your gebruikers table)
SELECT g.*
FROM gebruikers as g, sessions as s WHERE s.user_id = g.user_id
ORDER BY g.coins DESC
You would then use a row iterator to loop through the results and display "1", "2", "3", etc. The short version of which would look like
//Connect to database using whatever method you like, I will assume mysql_connect()
$sql = "SELECT g.* FROM gebruikers as g, sessions as s WHERE s.user_id = g.user_id ORDER BY g.coins DESC";
$result = mysql_query($sql,$con); //Where $con is your mysql_connect() variable;
$i = 0;
while($row = mysql_fetch_assoc($result,$con)){
$row['rank'] = $i;
$i++;
//Whatever else you need to do;
}
EDIT
In messing around with a SQLFiddle found at http://sqlfiddle.com/#!2/8faa9/6
I came accross something that works there; I don't know if it will work when given in php, but I figured I would show it to you either way
SET #rank = 0; SELECT *,(#rank := #rank+1) as rank FROM something order by coins DESC
EDIT 2
This works in a php query from a file.
SELECT #rank:=#rank as rank,
g.*
FROM
(SELECT #rank:=0) as z,
gebruikers as g
ORDER BY coins DESC
If you want to get the rank of one specific user, you can do that in mysql directly by counting the number of users that have more coins that the user you want to rank:
SELECT COUNT(*)
FROM `gebruikers`
WHERE `coins` > (SELECT `coins` FROM `gebruikers` WHERE `naam` = :some_name)
(assuming a search by name)
Now the rank will be the count returned + 1.
Or you do SELECT COUNT(*) + 1 in mysql...
Mysql query and PHP code that I'm using to get users from the database that meet certain criteria is:
$sql = mysql_query("SELECT a2.id, a2.name FROM members a2 JOIN room f ON f.myid = a2.id
WHERE f.user = 1 AND a2.status ='7' UNION SELECT a2.id, a2.name FROM members a2
JOIN room f ON f.user = a2.id WHERE f.myid = 1 AND a2.status ='7' GROUP BY id")
or die(mysql_error());
while ($r = mysql_fetch_array($sql))
{
$temp[] = '"'.$r[0].'"';
}
$thelist = implode(",",$temp);
The query that follows get the list of members with new galleries by using array from the previous query.
$ft = mysql_query("SELECT id, pic1 FROM foto WHERE id IN ($thelist) AND
pic1!='' ORDER BY date DESC LIMIT 10");
while ($f = mysql_fetch_array($ft))
{
echo $f['id']." - ".$f['pic1']."<br/>";
}
These queries working fine but I need to get the name for every user listed in second query. This data is in the first query in the column name. How can I get it listed beside '$f['id']." - ".$f['pic1']'?
While I might just alter the first query to pull the galleries at the same time, or change the second query to join and get the name, you could keep the same structure and change a few things:
In the loop after the first query when building $temp[], also build a lookup table of user id to user name:
$usernames[$r[0]] = $r[1];
Then in your output loop, use the id (assuming they are the same!) from the second query to call up the user name value you stored:
echo $f['id'] . " - " . $f['pic1'] . " - " . $usernames[$f['id']] . "<br/>";
I have a problem selecting 6 random friends
This is the query I've got so far:
$result = num_rows("SELECT * FROM friends WHERE member_id = '".$_SESSION['userid']."'");
if($result >= 6) {
$f_num = 6;
} else {
$f_num = $result;
}
for($i = 1; $i <= $f_num; $i++) {
$q_get_member_friends = mysql_query("SELECT * FROM friends WHERE member_id = '".$_SESSION['userid']."' ORDER BY rand() LIMIT 1");
$r_get_member_friends = mysql_fetch_array($q_get_member_friends);
echo $r_get_member_friends['friend_with'];
}
I want to select 6 random friends if the logged in user has more or equal to 6 friends
Stuck on this for a while now :/
Thanks for any help :)
If you use:
SELECT *
FROM friends
WHERE member_id = '".$_SESSION['userid']."'
ORDER BY rand()
LIMIT 6
If the person only has 3 friends, the query will only show those three - it doesn't mean that the query will always return six rows.
The best way I've found to select any number of random records is with OFFSET in the query.
Let's say you want 6 random records, so I'll borrow from an answer above and count the total number of friends in the database.
$sql = mysql_query("SELECT COUNT(*) AS total FROM friends WHERE member_id='". $_SESSION['userid'] ."'");
$get_count = mysql_fetch_array($sql); // Fetch the results
$numfriends = $get_count['total']; // We've gotten the total number
Now we'll get the 6 random records out of the total above (hopefully it's > 6),
$query = mysql_query("SELECT * FROM friends WHERE member_id='". $_SESSION['userid'] ."' LIMIT 6 OFFSET " . (rand(0, $numFriends));
while ($rows = mysql_fetch_array($query))
{
/// show your $rows here
}
Using OFFSET may not be the best or most efficient, but it's worked for me on large databases without bogging them down.
Never mind, I figured it out :)
Had to use while not for :'D
First select the number of friends that the user has:
"SELECT COUNT(*) as numFriends FROM friends WHERE member_id='".$_SESSION['userid']."'
...put that into a variable, let's call it "$numFriends"
Then:
for($z=0;$z<6;$z++)
{
$randomFriendIndex = rand(1,$numFriends);
//Get the friend at that index
}
change limit 1 to limit 6 on the eighth line.
Instead of SELECT * at the beginning, try SELECT COUNT(*) and use the actual return value instead of num_rows().
Your loop could generate duplicates. I would suggest trying OMG Ponies answer.
There is a whole chapter about random selection in the book SQL Antipatterns.
I have 4 Tables (listed bellow) and need:
get last 10 Chats from Room 3 without banned users
show nickname for fromuserid
HIDE Users $userid dont like to see table "HIDE"
Table 1 "chats"
ID(autoinc) fromuserid roomid text
1 23 3 bla
2 14 1 bla
3 11 3 bal
Table 2 "user" /shorted/
ID(autoinc) nickname banned
1 chris 0
2 paul 1 // 1 = banned
Table 3 "hide"
ID(autoinc) orguser hideuser
1 12 3
2 33 12
Right now i solved it with PHP Routine, but I have to go through EACH result and make always a new query, that needs too long;
$userid = 1; // actual user
// List all chats and show userid as nickname
$sql_com = "SELECT user.id, user.nickname, chats.text, chats.id ".
" FROM chats, user".
" WHERE ".
" chats.fromuserid = user.id ".
" AND chats.roomid = 3 ".
" AND user.banned != 1 ".
" ORDER BY chats.id DESC";
$result = mysql_query ($sql_com);
$count = 0;
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
$dontshow = false;
// Filter : dont show users $userid dont like to see (table "hide")
$sql_com2 = "SELECT id from hide WHERE ( (orguser = ".$userid.") AND (hideuser = ".$row[0].") ) ";
if ($result2 = mysql_query ($sql_com2))
{
if (mysql_num_rows($result2) > 0) $dontshow = true;
}
// Output
if ($dontshow == false)
{
$count++;
echo "Nickname: ".$row[1]." Text: ".$row[2];
}
if ($count > 10) break;
}
Btw. I made already some improvments, so the actual question may not fit with all answers (thanks for your help till now)
Finaly its now just about to integrate the filter "dont show people listed in table "hide" for my actual user".
I think you need something along these general lines. I've done it slightly different from your question. Instead of getting the top 10 then removing records. It gets the top 10 records which would not be hidden.
SELECT c.ID, c.fromuserid, c.roomid, c.text, u.nickname
FROM chats c
JOIN user u ON c.fromuserid = u.id
where c.roomid = 3 AND user.banned = 0
AND NOT EXISTS(
SELECT * FROM hide h
WHERE h.hideuser = c.fromuserid
AND orguser = $userid)
ORDER BY c.ID DESC
LIMIT 0,10
Not tested but it would be something like:
$sql_com = "SELECT us.id, us.nickname, ch.text, ch.id ".
" FROM chats ch, ".
" user us, ".
" hide hi, ".
" banned ba, ".
" WHERE ".
" us.id != hi.hideuser ".
" us.id != ba.user ".
" us.id = ch.fromuserid ".
" AND ch.roomid = 3 ".
" ORDER BY ch.id DESC LIMIT 0,10";
Although I can't immediately find a simple way to answer your question as-is, I can point you in the right direction:
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
Using subqueries should enable you to go and select from both blocked and hidden tables, and using those in your original query.