how to get max value of a sql database query in php - php

I want to find out the max value of sql data column on the basis of email id and username. (there is no primary entity)
To get the email id, i store the user email id from session.
here goes my code:
$emailid = $userRow['emailid'];
$sql = "select max(item) from product where email = '$emailid' AND username = 'arun'";
$result = $conn-> query($sql);
$row = $result->fetch_assoc();
echo "Max item : " .$row['result'];
It's giving me first value of sql table but not highest.

you can either change your column data-type or use CAST or CONVERT.
$sql = "SELECT MAX( CAST( `item` AS UNSIGNED) ) as max FROM `product` WHERE `email` = '$emailid' AND `username` = 'arun'";
If possible its better to change the data-type.

Try this,
$emailid = $userRow['emailid'];
$sql = "SELECT MAX(item) AS item FROM product WHERE email = '$emailid' AND username = 'arun'";
$result = $conn-> query($sql);
$row = $result->fetch_assoc();
echo "Max item : " .$row['item'];

Try this way,
$rowSQL = mysql_query( "SELECT MAX( ID ) AS max FROM `tableName`;" );
$row = mysql_fetch_array( $rowSQL );
$largestNumber = $row['max'];

Related

PHP MySQL Query with NOT LIKE specific id

I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');

update table for multiple users

I am looking to count the number of times 'yes' in present for a user in a table, then post the result into anther table for that same user. Both tables have the username. I would like this done for each user. I have the following but it is not working.
$sql = $item_count = "SELECT SUM(if(strike='yes',1,0)) AS strike_total FROM weekpicks WHERE username = 'username'";
// execute SQL query and get result
$sql_result = mysql_query($sql) or die (mysql_error());
if (!$sql_result) {
echo "Something has gone wrong!";
}
else {
//loop through record and get values
while ($row = mysql_fetch_array($sql_result)) {
$item_result = ($row = #mysql_query($item_count)) or die(mysql_error());
$strike_total = ($row = #mysql_result($item_result,"strike_total"));
$strikes = ($row = $strike_total ['strike_total']);
$username = $row["username"];
// the following will insert number of strikes into table for each user.
$sql = "UPDATE authorize SET strikes = '($strikes)' WHERE username='$username'";
//mysql_query(" UPDATE authorize SET " . "strikes = '" . ($strikes) . "' WHERE username='$username' ");
$result = mysql_query($sql) or die (mysql_error());
Just one query should be enough
Update for single user..
UPDATE authorize SET strikes = (select count(*) from weekpicks WHERE username = '$username' and strike='yes') WHERE username='$username';
For bulk update all users
UPDATE authorize as A SET strikes = (select count(*) from weekpicks B WHERE strike='yes' and A.username=B.username group by B.username)
Isn't that simple.

How to update a value by 1 if the new value inserted into the database clashes with value in the database?

I want to update the database of the sort order column to increase its value by one if the the new value inserted into the database clashes with the value that is already in the database. May I know how should I go about doing it? Please help! Thanks!
Below is my code (I am not sure whether am I on the right track):
$result = mysql_query("SELECT sortorder FROM information ORDER BY id ASC;");
if($result >= 1 ){
$i=1;
while ($initialorder = mysql_fetch_assoc($result))
{
$initialorder = $initialorder["sortorder"];
if ($sortorder == $initialorder ){
$result6 = mysql_query("SELECT * FROM information
WHERE `sortorder` = '$sortorder'");
$row6 = mysql_fetch_array($result6);
$removethis1 = $row6['id'];
$result7 = mysql_query("UPDATE information
SET `sortorder`= ((SELECT `sortorder`
FROM (SELECT MAX(`sortorder`) AS
'$initialorder' FROM information) AS '$initialorder') + 1)
WHERE id='$removethis1'");
}
$query = "INSERT INTO `information`
(`id`,`page`,`description`,`status`,`sortorder`,`keyword`,`date_added`)
VALUES
('$id','$title','$description','$status',
'$sortorder','$keyword','$date_added')";
$result = mysql_query($query, $conn);
header('Location: index.php?status=1&title='.$title);
$i++; }
}
You can do this:
INSERT INTO ON `information`
...
DUPLICATE KEY UPDATE
sortorder = '".$sortorder + 1." '

PHP - how to select from a table one query

I got a table that contains ID, Names, message, and time, I want to select from the table only one message query from each ID, Currently I select all the messages, this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo '</br>';
echo $msg;
}
That Shows all messages ordered by time, Is there is a way to select only one message query from each ID?
Thanks,
Klaus
If you want only one message you can use LIMIT like this
SELECT * FROM table ORDER BY time LIMIT 1
Or if you want only one message from some id then you can use GROUP BY
SELECT * FROM table ORDER BY time GROUP BY id
Sure, pretty straightforward
This will fetch all messages given ID:
$id = 10 //Get your id in any way you need
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo $msg;
}
and this will fetch only the first message given ID
$id = 10
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id LIMIT 1")or die(mysql_error());
$row = mysql_fetch_array($query));
if($row){
$msg = $row['message'];
echo $msg;
}else{
echo 'no messages for id '.$id;
}

PHP values going into db on refresh

Im trying to create something that if a user choses a match is going to win and that match wins the points enter automatically into DB .. Im doing fine untill the point that points enter only one time into DB. I mean validating properly but everytime on refresh points enter into DB . Help Please.
//Ndeshjet e fituara ose jo
echo "<h3>Ndeshjet e vendosura nga <b>$username</b> dhe Rezultatet:</h3><br/>";
$query = $db-> query("SELECT * FROM match_select WHERE user_id='$username'");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$match = $db->query("SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'");
$id = $row['match_id'];
$liga = $row['liga'];
$koeficent = $row['selected_koef'];
if($match->rowCount($match)){
echo "";
}else{
if ($row['result'] == $row['final']){
$hey = "style='color: green;' ";
$match = $db -> query("INSERT INTO winner (user_id, match_id, koef, final, liga) VALUES ('$username','$id', '$koeficent', '1', '$liga')");
}else if ($row['final']== ""){
$hey = "style='color: black;' ";
}else{
$hey = "style='color: red;' ";
}
}
}
In respect to the code provided and as I understand it;
Select all the matches for that username (loop through all matches)
Validation: check if this has been added to the winner table already
If so ignore it, otherwise if result = final is same (don't know the context here) then store..
The problem is when you select data for validation, they are null value you should declare them before query...as here
$match = $db->query("SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'");
$id = $row['match_id'];
$liga = $row['liga'];
$koeficent = $row['selected_koef'];
it should be
$id = $row['match_id'];
$liga = $row['liga'];
$koeficent = $row['selected_koef'];
$match = $db->query("SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'");
This coluld be the reason when refereshing everytime it doesn't find any results so inserts.... my recommendation is to have SQL in a different variable and for testing purposes you can dump it on screen such as
$sql = "SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'";
echo $sql; //to see whats going on
$match = $db->query($sql);
Hope this helps mate

Categories