I am trying to make two queries providing $result and $result2. I would like to subtract the two results to create a total for the vote (negative vote being possible). Therefore on an empty query the result value would have to be zero.
My subtraction function isn't working. Does anyone know what I am doing wrong? I am getting no result.
Thanks in advance!
My code:
$result = mysql_query('SELECT COUNT(*) FROM comment_votes WHERE vote_com_writer_id = "'.$d['user_id'].'" AND vote_com_rank = "1"');
$positive_votes = mysql_result($result, 0);
$result2 = mysql_query('SELECT COUNT(*) FROM comment_votes WHERE vote_com_writer_id = "'.$d['user_id'].'" AND vote_com_rank = "2"');
$negative_votes = mysql_result($result2, 0);
list($vote) = $positive_votes - $negative_votes;
Start with the basics.
Confirm that your sql queries work by manually executing them against your database.
Confirm that $postive_votes and $negative_votes are what you expect with something like the following:
echo 'Positive Votes: '.$positive_votes.', Negative Votes: '.$negative_votes.
remove list($vote) as it is not being used correctly. The list function is intended for arrays not the results of subtraction. Replace that line with the following:
$total_votes = $positive_votes - $negative_votes;
echo 'Total Votes:'.$total_votes;
.
Related
I have a table called feedbacks that looks like this:
id user type
1 JOhnT Positive
2 JOhnT Negative
3 Sarah Positive
4 JOhnT Positive
5 JOhnT Neutral
....................
I need to get the percentage of POSITIVE feedback for each user using PHP.
I tried something like this which i know it is wrong:
$sql = "SELECT type, count(*),
concat(round(( count(*)/(SELECT count(*) FROM feedbacks WHERE user='JOhnT' AND type='POSITIVE') * 100 ),2),'%') AS percentage
FROM feedback
WHERE user='$email' AND type='positive' GROUP BY type";
$query = mysqli_query($db_conx, $sqlJ);
echo $sql;
Could someone please advice on how to achieve this?
EDIT:
Based on the comments, this is what i have so far:
$sql = "SELECT * FROM feedbacks WHERE user='JOhnT' AND type='POSITIVE'";
$query = mysqli_query($db_conx, $sql) or die(mysqli_error($db_conx));
$productCount = mysqli_num_rows($query);
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
///do I need to calculate the percentage here?//
//if so, how?////
}
}
I ended up creating an array and push each $row in my whole loop into the array and then calculate the percentage like this:
$c = count($values);
$array = $values;
function array_avg($array, $round=1){
$num = count($array);
return array_map(
function($val) use ($num,$round){
return array('count'=>$val,'avg'=>round($val/$num*100, $round));
},
array_count_values($array));
}
$rating = 0;
if($c > 0){
$avgs = array_avg($array);
$rating = $avgs["positive"]["avg"];
}
This works fine for now.
You can do this a conditional average. In MySQL, you could phrase this as:
select user, avg(type = 'Positive') positive_ratio
from feedback
group by user
This gives you, for each user, a value between 0 and 1 that represents the ratio of positive types. You can multiply that by 100 if you want a percentage.
If you want this information for a single user, you can filter with a where clause (and there is no need to group by):
select user, avg(type = 'Positive') positive_ratio
from feedback
where user = 'JOhnT'
Side note: user is a MySQL keyword, hence not a good choice for a column name.
I need to get number of rows from table as string.
I execute this code:
$phql = "SELECT COUNT(*) FROM Model WHERE id = $this->id";
$count = $this->getModelsManager()->createQuery($phql)->execute();
Now $count is Phalcon\Mvc\Model\Resultset\Complex object. To get a proper result I need to do something like that:
$count[0]->{0}
In my opinion this is awful. Is there any other way to get this result?
Few solutions:
1) Use simple queries:
$count = $this->db->fetchOne('SELECT COUNT(*) AS total FROM products');
2) Model aggregations
$count = Products::count(
"area = 'Testing'"
);
More info and methods: https://docs.phalconphp.com/ar/3.2/db-models in section Generating Calculations
3) If you insist of using executeQuery() you should add getFirst() in order to get only one result. Similar to PDO's fetchOne().
$phql = "SELECT COUNT(*) AS total FROM Models\Products";
$count = $this->modelsManager->executeQuery($phql)->getFirst();
I'm trying to create a pagination for my PDO query. I cant figure it out. I've tried numerous google searches, but nothing that will work for me. [I probably didn't search hard enough. I'm not sure]
This is my code:
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
foreach ($nodes2 as $n1) {
echo "text";
}
I want to be able to limit 10 comments per page, and use $_GET['PAGE'] for the page.
Something that I tried
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
$page_of_pagination = 1;
$chunked = array_chunk($nodes2->get_items(), 10);
foreach ($chunked[$page_of_pagination] as $n1) {
echo "text";
}
If someone could help out, I appreciate it.
You need to limit the query that you are performing, getting all values from the database and then limiting the result to what you want is a bad design choice because it's highly inefficient.
You need to do this:
$page = (int)$_GET['PAGE']; // to prevent injection attacks or other issues
$rowsPerPage = 10;
$startLimit = ($page - 1) * $rowsPerPage; // -1 because you need to start from 0
$sql2 = "SELECT * FROM comments WHERE shown = '1' ORDER BY ID DESC LIMIT {$startLimit}, {$rowsPerPage}";
What LIMIT does:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants
More information here: http://dev.mysql.com/doc/refman/5.7/en/select.html
Then you can proceed getting the result and showing it.
Edit after comment:
To get all the pages for display you need to know how many pages are there so you need to do a count on that SELECT statement using the same filters, meaning:
SELECT COUNT(*) as count FROM comments WHERE shown = '1'
Store this count in a variable. To get the number of pages you divide the count by the number of rows per page you want to display and round up:
$totalNumberOfPages = ceil($count / $rowsPerPage);
and to display them:
foreach(range(1, $totalNumberOfPages) as $pageNumber) {
echo '' . $pageNumber . '';
}
I have a MySQL, PHP code as follows.
$sql = "SELECT * FROM shipschedule WHERE ship_date BETWEEN '2016-08-01' AND '2016-8-31'";
$result = $mysqli->query($sql);
$e = array();
while($r = $result->fetch_array()) {
$rows = array();
$rows['title'] = $r['title'];
$rows['start'] = $r['ship_date'];
array_push($e, $rows);
}
echo json_encode($e);
The above php code echos
[{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
My question is how I can echo the above as follow instead. Please see that duplicate start dates will be removed by title.
[{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
title 111 has the same 3 start dates, and I need to display it like
{"title":"111","start":"2016-08-10"},
title 222 has the same 2 start dates, and I need to display it like
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
You could prevent receiving duplicates, and reduce requesting unnecessary data by adjusting your query.
SELECT DISTINCT title, start FROM ...
It would be much easier (and probably faster too) to just get the right (unique) data from MySQL. This can be achieved with the distinct modifier:
SELECT DISTINCT title, start
FROM shipschedule
WHERE ship_date BETWEEN '2016-08-01' AND '2016-8-31'
Trying to search through a column in a db, and pull out the total number of males, and total number of females.
This data is stored in the db as f and m in the whatsex column.
$query = "SELECT whatsex, COUNT(*) FROM soberdata GROUP BY whatsex";
$result = mysqli_query($connection,$query) or die(mysql_error());
$sexdb = mysqli_fetch_array($result);
$totalmale = $sexdb['m'];
$totalfemale = $sexdb['f'];
echo $totalfemale." & ".$totalmale;
This code outputs nothing. What am I doing wrong?
$sexdb have only "whatsex" and "COUNT(*)" columns. You should use one of them
try
print_r($sexdb);
and look if some of results meet your needs
Your query is going to return a whatsex value, and a COUNT(*) value, not m or f. Doing a var_dump($sexdb) would show you what's in the array.
You are treating a multi-dimensional array as flat. You could do this to flatten it
$query = "SELECT whatsex, COUNT(*) as total FROM soberdata GROUP BY whatsex";
while ($row = mysqli_fetch_array($result)) {
$$row['whatsex'] = $row['total']; // this makes a variable ($m or $f) using the value of the row
}
$totalmale = !empty($m) ? $m : 0;
$totalfemale = !empty($f) ? $f : 0;
You should empty check the results of the db in case there is no male or female entries to avoid errors.