MySQL update table on vote script - mysql

I have a voting script on my message board. When somebody votes, it uses vote.php:
$check_query = " insert into m_votes set votes = {$vote_type}, ip = '$user_ip', messageid = $mid, name = '$name', messageby = '$mbu'";
$check_query_result = mysql_query($check_query) or die(mysql_error());
// return back total votes
$votes_query = "select sum(votes) as votes from m_votes where messageid = $mid";
$votes_query_result = mysql_query($votes_query) or die(mysql_error());
$votes_query_row = mysql_fetch_array($votes_query_result);
echo $votes_query_row['votes'];
// update score on guestbook_message table
$update = "UPDATE guestbook_message SET score = $votes_query";
The problem is with the last line of code. The 'score' field is on a different table to the one the votes information is held.I just want it so that when somebody votes on a message, it gets the sum of votes for that message, and updates the 'score' field on the guestbook_message table. But the code I have doesn't do this. it doesn't show a syntax error either.

$update = 'UPDATE guestbook_message SET score = ' . $votes_query_row['votes'];
mysql_query($update) or die(mysql_error());

Related

How to convert this query to doctrine DQL

SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
select 1
from `distribution_mobiletokens`
where userid = '20'
and deviceid = dm.deviceid
and created > dm.created
)
What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.
My database looks like below.
For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))
Things I've Tried
$mobiletokens = $em->createQueryBuilder()
->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
->from('AppBundle:MobileTokens', 'u')
->leftJoin('u.companyId', 'company')
->leftJoin('u.userId', 'user')
->where('u.status = 1 and user.id = :userid')
->setParameter('userid',(int)$jsondata['userid'])
->groupby('u.apntoken')
->getQuery()
->getResult();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}
die();
This gives me the incorrect response of
63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
Any help here is appreciated!
Other Information
Data with SELECT * FROM
Data after using the SQL I provided up top.
You could use a subselect created with the querybuilder as example:
public function selectNewAppToken($userId)
{
// get an ExpressionBuilder instance, so that you
$expr = $this->_em->getExpressionBuilder();
// create a subquery in order to take all address records for a specified user id
$sub = $this->_em->createQueryBuilder()
->select('a')
->from('AppBundle:MobileTokens', 'a')
->where('a.user = dm.id')
->andWhere('a.deviceid = dm.deviceid')
->andWhere($expr->gte('a.created','dm.created'));
$qb = $this->_em->createQueryBuilder()
->select('dm')
->from('AppBundle:MobileTokens', 'dm')
->where($expr->not($expr->exists($sub->getDQL())))
->andWhere('dm.user = :user_id')
->setParameter('user_id', $userId);
return $qb->getQuery()->getResult();
}
I did this for now as a temporary fix, not sure if this is best answer though.
$em = $this->em;
$connection = $em->getConnection();
$statement = $connection->prepare("
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid=:userid
and not exists (
select 1
from `distribution_mobiletokens`
where userid = :userid
and deviceid = dm.deviceid
and created > dm.created
)");
$statement->bindValue('userid', $jsondata['userid']);
$statement->execute();
$mobiletokens = $statement->fetchAll();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}

Select a value from table and reserve it

Low level question but, I understand that you can select elements from a table using:
$sql = "SELECT blah FROM TABLE WHERE this = 'something' ";
But when I try to select a specific value from my table, where let's say a user has no tries left so if I try to grab how many tries they have left with:
$sql = "SELECT tries FROM table WHERE user = 'something'";
How would I grab that value specifically if it was 5 or 9? I tried setting a variable equal to something I $sql off my table but it doesn't grab the value.
Edit
I have a database that has a table called Item which contains: id, name, value, and stock of a particular item. If a user wants to order that item I will first check it if's in stock with a function, to see if it is not in stock then a error message is printed, otherwise accept the order.
Extremely primitive since I'm just trying to get grab the stock value first.
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' .$query.''; //test purposes
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error connecting to database server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
echo '' .$sql2. ''; //test purposes
whats the correct way to assign the value from that specific stock to a variable?
If you want to grab rows with a set of possible values you can use 'IN' such as:
Get all columns from users table where users have 5 or 9 tries:
SELECT * FROM users WHERE tries IN('5', '9'); or
If you want to select where the user has no tries left, assuming the tries column is a numeric type you can look for rows with 0 tries:
Get all columns from Item table where stock is 0:
SELECT * FROM db_inv.Item WHERE stock = '0';
Get all columns from users table where tries is 0:
SELECT * FROM users WHERE tries = '0';
As for your php code you should be able to do the following:
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' . $query; //test purposes
$mysql_handle = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to database server");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
$results = mysqli_query($mysql_handle, $sql1);
if (!empty($results) && mysqli_num_rows($results) > 0) {
while($rec = mysqli_fetch_array($results)) {
echo $rec['item_stock'];
}
}

Add 2 numbers together, one from a database result and the other from post array

I'm trying to add 2 numbers together. The first number is from the database say it's 150 it comes from the $sql1 and the second number comes from the form and is in the POST array say it's 25. Once the $sql2 is run the number in the database should be 175 but it's still 150, any ideas on what i'm missing/doing wrong?
$sql1 = "SELECT points FROM users WHERE userID = ?";
$qc1 = $pdo_conn->prepare($sql1);
$qc1->execute(array($_POST['userID']));
$result = $qc1->fetch(PDO::FETCH_ASSOC);
$points = $result + $_POST['addPoints'];
$sql2 = "UPDATE users SET points = ? WHERE userID = ?";
$qc2 = $pdo_conn->prepare($sql2);
$qc2->execute(array($points, $_POST['userID']));
Based on your code, the $result variable is going to return the response from the database as an array. Thus, in order to get the number, you need to pass the field name from your SELECT statement.
Therefore,
$points = $result + $_POST['addPoints'];
should be:
$points = $result['points'] + $_POST['addPoints'];

Query (mysql) should only update if $sqltext < $_POST[Score]

I have the following query:
$sqltext = "SELECT Score FROM HighScore ".
"WHERE fbID='$_POST[fbID]' AND ".
"Layout='$_POST[Layout]'";
$result = mysql_query($sqltext);
if(mysql_num_rows($result)>0){
$sql = "UPDATE HighScore SET Score = '$_POST[Score]', ".
"Time = '$_POST[Time]', ".
"Stars = '$_POST[Stars]' ".
"WHERE fbID = '$_POST[fbID]' AND Layout = '$_POST[Layout]'";
} else {
$sql = "INSERT INTO HighScore (fbID, Layout, Score, Time, Stars) ".
"VALUES ('$_POST[fbID]','$_POST[Layout]',".
"'$_POST[Score]','$_POST[Time]','$_POST[Stars]')";
}
What does it do? Well it checks if a row is in the database or not (there is always just 1 row or none). If there is no row, it inserts a new one in the database. If the row is present it will update the row. This all works OK.
$sqltext will give a value. This value can be 234, 3424342 or even -392. If this value is smaller than the '$_POST[Score]' value, it should update the row. Currently it doesn't and I can't seem to get this working properly. So how can I make it so, that if $sqltext (which is Score from the db) < '$_POST[Score]' it should update the row and else ignore it? (also not insert).
You could also add a UNIQUE KEY constraint on (fbID, Layout) and then just use one query:
$sql = "
INSERT INTO HighScore
(fbID, Layout, Score, Time, Stars)
VALUES ( '$_POST[fbID]', '$_POST[Layout]'
, '$_POST[Score]', '$_POST[Time]', '$_POST[Stars]'
)
ON DUPLICATE KEY
UPDATE
Score = GREATEST(Score, VALUES(Score))
, Time = VALUES(Time)
, Stars = VALUES(Stars)
";
$sqltext= "SELECT Score FROM HighScore WHERE fbID='$_POST[fbID]'AND Layout='$_POST[Layout]'"; $result = mysql_query($sqltext);
if(mysql_num_rows($result)>0){
if ($row = mysql_fetch_assoc($result))
{
if ($row['Score'] < $_POST['Score'])
{
$sql="UPDATE HighScore SET Score = '$_POST[Score]', Time = '$_POST[Time]', Stars = '$_POST[Stars]' WHERE fbID = '$_POST[fbID]' AND Layout = '$_POST[Layout]'";
}
}
}else{
$sql="INSERT INTO HighScore (fbID, Layout, Score, Time, Stars) VALUES ('$_POST[fbID]','$_POST[Layout]','$_POST[Score]','$_POST[Time]','$_POST[Stars]')";
}
I think this is what you want. But it does not do anything, if there is a row AND the score is higher than the Score in POST['Score']

how can I connect these two tables in sql?

i need to take only the items from the table "__sobi2_item" that are in the same country of the user.And use this results for the rest of the function Showupdatelisting. This is my php script:
<?php
function showUpdatedListing()
{
//i found the user country field value...
global $database;
$user =& JFactory::getUser();
$userId = $user->get( 'id' );
$sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= 'FIELD_COUNTRY'";
$database->setQuery( $sql );
$fieldID = $database->loadResult();
$sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}";
$database->setQuery( $sql );
$usercountry = $database->loadResult();
// From all the entries i take only ones that have country field like the user has...
$query = "SELECT `data_txt`, `itemid`, `fieldid` FROM `#__sobi2_fields_data` WHERE (`fieldid` = 6) AND ('data_txt' = {$usercountry})";
$database->setQuery($query);
$ResultsArray = $database->loadObjectList();
// We need something here like a Query to load only the entries from $ResultsArray... ??
//....instead of this...
$config =& sobi2Config::getInstance();
$database = $config->getDb();
$now = $config->getTimeAndDate();
$query = "SELECT itemid FROM #__sobi2_item WHERE (published = 1 AND publish_down > '{$now}' OR publish_down = '{$config->nullDate}') ORDER BY last_update DESC LIMIT 0, 30";
$database->setQuery($query);
$sids = $database->loadResultArray();
// ......... show update function goes on...
?>
can anyone help me to connect and adjust these query? thanks.
NB:with the last query (4) i need to filter items of the $ResultsArray taking only ones published and ordering them by last_update. i know it is wrong and now there is no connection with the query before. This is how i have tables in mysql:
_sobi2_fields_data:
itemid
fieldid
data_txt --->(is a description column for each field)
_sobi2_item:
itemid
published --->( 1 if true, 0 if false )
last_update --->(date of the last update for the item, also equal to the publication date if there are no changes)
thanks.
I don't know what you are trying to ask as well. Your last query (number 4) doesn't make sense to me, how is it linked to the above queries?
[EDIT] I've linked your 4th table above assuming itemid is the primary key for the items in sobi2_item table and that the value is linked to the sobi_fields_data table via itemid.
SELECT
cf.id,
sfd.data_txt,
sfd.itemid,
sfd.fieldid
FROM #__community_fields cf
INNER JOIN #__community_fields_values cfv ON cf.id=cfv.field_id
INNER JOIN #__sobi2_fields_data sfd ON cfv.value=sfd.data_txt
INNER JOIN #__sobi2_item si ON sfd.itemid=si.itemid
WHERE cf.fieldcode='FIELD_COUNTRY'
AND cfv.user_id=$userId
AND sfd.fieldid=6
AND si.published=1
AND (si.publish_down > '{$now}' OR si.publish_down = '{$config->nullDate}')
ORDER BY si.last_update DESC LIMIT 0, 30
Good luck!