Try to separate a loop result - php

I'm making a poll, and I have a php script to get the percents of the number voted for that poll option. When i run a query I just keep getting 0 for the options. How can I make it so that each $val1 has a different number according to the row total in the database for?
For example: poll option 1 has 1 vote, poll option 2 has 1 vote, poll option 3 has 0 and poll option 4 has 0. and the query would output 50 option one and option 2 and 0 for option 3 and four.
My code
$poll = $db->fetch("SELECT * FROM home_poll ORDER BY id DESC LIMIT 1");
$option_sql = $db->query("SELECT total FROM home_polls_option WHERE poll_id = '" . $poll['id'] . "'");
while ($row = mysqli_fetch_array($option_sql)) {
$val1 = $row['total'];
}
$poll_votess = $db->query("SELECT * FROM home_polls_vote WHERE poll_id = '" . $poll['id'] ."'");
$val2 = $poll_votess->num_rows;
$res = round ($val1 / $val2 * 100);
$options1 .= ' <script>
var doughnutData = [
{
value: ' . $res . ',
color:"#F7464A"
},
{
value : ' . $res . ',
color : "#46BFBD"
},
{
value : ' . $res . ',
color : "#FDB45C"
},
{
value : '. $res.',
color : "#949FB1"
}
];
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);
</script>';
Database :
home_polls_vote: http://prntscr.com/2vd1lt
home_polls_option: http://prntscr.com/2vd1k7

In while loop you have took in $val1 just latest row value and because it is 0 votes, you got everywhere 0. You need to put it into array and later on use $res as array also so you can print different values down there in your script.
EDIT:
You can try something like this. First fetch total number of votes, then put percent in result in while loop.
$poll = $db->fetch("SELECT * FROM home_poll ORDER BY id DESC LIMIT 1");
$option_sql = $db->query("SELECT total FROM home_polls_option WHERE poll_id = '" . $poll['id'] . "'");
$poll_votess = $db->query("SELECT * FROM home_polls_vote WHERE poll_id = '" . $poll['id'] ."'");
$number_of_votes= $poll_votess->num_rows;
while ($row = mysqli_fetch_array($option_sql)) {
$res[] = round ($row['total'] / $number_of_votes * 100);
}
$options1 .= '<script>
var doughnutData = [
{
value: ' . $res[0] . ',
color:"#F7464A"
},
{
value : ' . $res[1] . ',
color : "#46BFBD"
},
{
value : ' . $res[2] . ',
color : "#FDB45C"
},
{
value : '. $res[3].',
color : "#949FB1"
}
];
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);
</script>';

Use mysql it'self for calculation this will avoid many lines of code and ease to process
http://dev.mysql.com/doc/refman/5.0/en/precision-math-rounding.html
https://dev.mysql.com/doc/refman/5.0/en/case.html
$sql = " SELECT ROUND(COUNT(hpv.id)/hpo.total * 100) AS res
FROM home_polls_option AS hpo
JOIN home_polls_vote AS hpv ON hpv.poll_id = hpo.poll_id
WHERE hpv.poll_id=$poll ['id']
GROUP BY hpo.value";

Related

Select ID from one table and insert in another table with while loop

The code below works on three tables:
iStock, iInvoicebook, iInvoiceitems
iInvoicebook and iInvoiceitems are linked bt ID and dInvoicebookFKEY,
iStock - This table stores all products with clients name and quantity. To generate an invoice, the code gets DISTINCT clients and inserts to iInvoicebook.
After this, the code inserts all product details from the iStock table to iInvoiceitems.
The code below mostly works, except that when I try to get iInvoicebook ID and try to insert it (as foreign key) in iInvoiceitems, it inserts the old ID of iInvoicebook based on clientID.
I want the newly added ID of iInvoicebook to be inserted in iInvoiceitems.
if($CurrDate == $LastDayofMonth)
{
// Get Distinct clients and add it into Main table "Invoicebook"
$getClients = "SELECT DISTINCT iClientName AS CLT, Product from stock where quantity > '0' AND InvoiceDate ='$LastDayCM'";
$stmt = ExecuteQuery($getClients); // execute the query
if ($stmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $stmt->fetch()) { // begin of loop
$NewNo = Executerow("Select max(ibInvoiceNo) AS NEXTNO from invoicebook");
$Nor = $NewNo["NEXTNO"] + 1 ;
$instInInvoice = ExecuteStatement("INSERT INTO invoicebook (ibClientName, Product, InvoiceNo)
Values( '".$row["CLT"]."','".$row["Product"]."', '".$Nor."')");
}
}
// Now no Disticnt value. Get all stock values of related client and insert into "invoiceitems" table
$getDetails = "select iClientID, product, quantity from stock where quantity > '0' AND InvoiceDate ='$LastDayCM' AND iClientName = '".$getClients["iClientName"]."'";
$dstmt = ExecuteQuery($getDetails); // execute the query
if ($dstmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $dstmt->fetch()) { // begin of loop
$InvoiceFKEY = Executerow("Select INVID from invoicebook where dClientID = '".$row["iClientID"]."'");
$DetailsInsrt = ExecuteStatement("INSERT INTO invoiceitems (dproduct, dQuantity, dRate, dInvoicebookFKEY)
Values( '".$row["product"]."','".$row["quantity"]."','".$rate."', '".$InvoiceFKEY["INVID"]."')");
}
}
}
here your code with some comments :
if ($CurrDate == $LastDayofMonth) {
// Get Distinct clients and add it into Main table "Invoicebook"
$getClients = "SELECT DISTINCT iClientName AS CLT, Product from stock where quantity > '0' AND InvoiceDate ='$LastDayCM'";
$stmt = ExecuteQuery($getClients); // execute the query
if ($stmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $stmt->fetch()) { // begin of loop
$NewNo = Executerow("Select max(ibInvoiceNo) AS NEXTNO from invoicebook");
$Nor = intval($NewNo["NEXTNO"]) + 1;
$instInInvoice = ExecuteStatement("INSERT INTO invoicebook (ibClientName, Product, InvoiceNo) "
. " Values ( '" . $row["CLT"] . "','" . $row["Product"] . "', '" . $Nor . "') "
. " on duplicate key update InvoiceNo='{$Nor}'"); //EDIT : Dont know but should get PK key
// => this could generate multiple line in you DB
// => and don't know your DB structure but for me, should be better to link with stock.iClientID than stock.iClientName
//
}
}
/**
* From here why create second loop?
* Should have fonction "get_last_id" from your DB object and if the field invoicebook.INVID is AI should get last one
*
*/
// Now no Disticnt value. Get all stock values of related client and insert into "invoiceitems" table
$getDetails = "select iClientID, product, quantity from stock where quantity > '0' AND InvoiceDate ='$LastDayCM' "
. " AND iClientName = '" . $getClients["iClientName"] . "'"; // - EDIT : this is empty var => NULL
$dstmt = ExecuteQuery($getDetails); // execute the query
if ($dstmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $dstmt->fetch()) { // begin of loop
$InvoiceFKEY = Executerow("Select INVID from invoicebook where dClientID = '" . $row["iClientID"] . "'");
$DetailsInsrt = ExecuteStatement("INSERT INTO invoiceitems (dproduct, dQuantity, dRate, dInvoicebookFKEY)
Values( '" . $row["product"] . "','" . $row["quantity"] . "','" . $rate . "', '" . $InvoiceFKEY["INVID"] . "')");
//Same : duplicate key => what the frequence of this routine?
// ($CurrDate == $LastDayofMonth) => I guess once by day, everyday and run only last month day
// Or action from you : mean you can run this script more than once a day => duplicated data
// $LastDayCM == $CurrDate == $LastDayofMonth ??????
}
}
}
If I understand well, you should maybe change your function with a code like this :
if ($CurrDate == $LastDayofMonth) {
//First should escape your variable
$getClients = sprintf("SELECT DISTINCT `iClientName` AS CLT,`iClientID` as 'IdClient', `Product`,`quantity` " // should
. " from `stock` "
. " where `quantity`>%d AND InvoiceDate='%s' "
, 0 // quantity
, escapeFunction($LastDayCM) //mysqli_real_escape($linkSql, $LastDayCM) : don't know where your data come from
);
$stmt = ExecuteQuery($getClients); // execute the query
if ($stmt->rowCount() > 0) { // Useless for me
while ($row = $stmt->fetch()) { // begin of loop
$NewNo = Executerow("Select max(`ibInvoiceNo`) AS NEXTNO from `invoicebook`");
$Nor = intval($NewNo["NEXTNO"]) + 1; // NEXTNO can be null if no data
$instInInvoice = ExecuteStatement(
sprintf("INSERT INTO `invoicebook` (`dClientID`,`ibClientName`, `Product`, `InvoiceNo`) "
. " Values (%d, '%s','%s', %d) "
, $row['IdClient'] // add ID ??? and not sure about column name
, escapeFunction($row["CLT"])
, escapeFunction($row["Product"])
, $Nor
)
);
//Get last id 2 options : get_last_id function or new select statement :
//option 1 : better
$INVID = getLastIdFunction();
//Option 2 : depend of your DB structure
$InvoiceFKEY = Executerow(
sprintf("Select INVID from `invoicebook`"
. " where dClientID =%d and InvoiceNo=%d"
, $row['IdClient']
, $Nor
)
);
$tmpStatement = ExecuteQuery($InvoiceFKEY); // execute the query
$INVID = $tmpStatement->fetch()['INVID'];
//Add new invoiceitems
$DetailsInsrt = ExecuteStatement(sprintf("INSERT INTO `invoiceitems` "
. " (`dproduct`, `dQuantity`, `dRate`, `dInvoicebookFKEY`) Values "
. " ( '%s',%d,%0.2f, %d)"
, escapeFunction($row["Product"])
, $row["quantity"]
, $rate // where come from? format? 00000.00 ???
, $INVID
)
);
ExecuteQuery($DetailsInsrt);
}
}
}
Without DB structure and more details, hard to go further

Joining two tables based off a condition SQL

I am building an android app that uses geo location. I am trying to improve my overall app to improve its smoothness while running. I am using volly to connect to a php page on my web sever where the php page can then access my phpmyadmin database. My php page for updating locations is a horrible mess and I was hoping it can be fixed with the right sql query.
Lets get down to it.
So I have a table named users
and a table named friends
In this particular example david is friends with mark and jack. Also to clarify mark and jack are friends with david.
What I need to do is Write a query if given a user ID say for example 3 that will produce a table of that person and his friends ID, cordsV1, cordsV2 without any duplicate IDs in the table.
I was able to get this to work with using loops and variables ect but as I said it is a horrible mess.
Here is my current all sql query attempt:
SELECT DISTINCT ID, cordsV1, cordsV2 FROM `friends`,`users` WHERE user_one_ID = 1 AND status = 1;
HOWEVER this just returns all of the user IDs from the user table. I am really bad with sql so if someone could point me in the right direction it would be much appreciated.
Here is my horrible mess of code if you were wondering:
<?php error_reporting(E_ALL | E_STRICT); ?>
<?php
$THIS_USER_ID = $_GET['THIS_USER_ID'];
try {
$one = 1;
$db = new PDO("");
$sql = "SELECT * FROM friends WHERE user_one_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "' OR user_two_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "'";
$rows = $db->query($sql)
->fetchAll(PDO::FETCH_ASSOC);
$printMe = [];
foreach($rows as $row){
$printMe[] = $row;
}
$jsonArr = json_encode($printMe);
$characters = json_decode($jsonArr, true);
// Getting the size of the sample array
$size = sizeof($characters);
$neg = -1;
$sql2 = "SELECT * FROM users WHERE ID = '" . $neg . "'";
$sql3 = "";
$sql4 = "";
for ($x = 0; $x < $size; $x++ ){
if ($characters[$x]['user_one_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1){
$hold = $characters[$x]['user_two_ID'];
$sql3 = $sql3 . " OR ID = '" . $hold . "'";
} else if($characters[$x]['user_two_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1) {
$hold = $characters[$x]['user_one_ID'];
$sql4 = $sql4 . " OR ID = '" . $hold . "'";
}
}
$sql5 = $sql2 . $sql3 . $sql4;
$sql7 = "SELECT * FROM users WHERE ID = '" . $THIS_USER_ID . "'";
$printMe2 = [];
$rows3 = $db->query($sql7)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows3 as $row3){
$printMe2[] = $row3;
}
$rows2 = $db->query($sql5)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows2 as $row2){
$printMe2[] = $row2;
}
$jsonArr2 = json_encode($printMe2);
echo $jsonArr2;
$db = null;
} catch(PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>
Get the user-data
SELECT
*
FROM
users
WHERE ID = ?
Get the user-data of friends
SELECT
users.*
FROM
friends
JOIN
users ON users.ID = friends.user_two_ID
WHERE
friends.user_one_ID = ?
Better use prepared statements, or your app wont be alive very long due to SQL-Injections.
You also want to have a look at meaningful names.

images pagination - how to get all params in one single query

I have a pagination system for viewing images from database.
So each time I click on a next / prev buttons I need three variables
Question - is there a way to get them in one single query and not using a separate query for each of them?
$lm = 100; // limit per page
$off = 0; // offset - click on next prev buttons
$dim = '960 x 540'; // img dimensions
function get_images($lm, $off, $dim){
global $db;
//firstly I need total number of images
$st = $db->query("select count(*) as cnt from images");
$total = $st->fetchColumn();
//then I need number of 960 x 540 images
$st = $db->query("select * from images where dim = '" . $dim . "'");
$insel = $st->rowCount();
//then I need number of viewed images on a pagination system
$st = $db->query("select * from images where dim = '" . $dim . "' order by date desc limit " . $lm . "
offset " . $off);
$inview = $st->rowCount();
$st = $db->query("select * from images where dim = '" . $dim . "' count(id) over(partition by id) as cnt count(dim) over(partition by dim) as insel order by date desc limit " . $lm . " offset " . $off);
But make sure you are using MySQL version greater than or equal to 8.0

getting wrong count of selected rows [duplicate]

This question already has an answer here:
Count always returns 1...but does it exist?
(1 answer)
Closed 3 years ago.
function c_save( $a, $status, $b ) {
global $db;
$st = $db->query( "select count(id) from steps where cas = '" . $a . "' and status = '" . $status . "' and title = '" . $b . "'" );
$count = $st->rowCount(); echo $count;
}
the echoed result - 1
Manually checking the table (20 rows total) - there is no such a row having cas = $a... so the result should be 0.
you are performing the count at the query level. the result of your query is a single line containing maybe 20.
if you want to get the number of records ', you can just get the value returned by the query or do not count within sql to get the full resultset and let php make the count.
Try this:
function c_save($a, $status, $b){
global $db;
$st = $db->query("select id from steps where cas = '" . $a . "' and status = '" . $status . "' and title = '" . $b . "'");
$count = $st->rowCount();
echo $count;
}

PHP & Mysql Not ordered correctly

I have latest MySQL version (5.5) and this is the screenshot of groupid field
I didn't touch anything yet, but some cells are not ordered correctly like this
But if I click groupid name in the top, it will ordered correctly like this:
Below PHP code output is like first screenshot above, that are not ordered correctly. Please help how to make the output ordered correctly, like it is displayed in the second screenshot above,
Maybe add code like this : order by id asc, but which is the right place to add it below?
$group_ids = explode(" ", $options['groupchoice_ids']);
$groupsql = "SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first = true;
foreach($group_ids as $value)
{
if (!$first)
{
$groupsql = $groupsql . " OR ";
}
else
{
$first = false;
}
$groupsql = $groupsql . " id = '" . $value . "' ";
}
$kh_optionsgroup = '<select name = "accounttype">';
$checksec = $db->query_read($groupsql);
if ($db->num_rows($checksec))
{
while ($lboard = $db->fetch_array($checksec))
{
$kh_optionsgroup = $kh_optionsgroup . "<option value
='" . $lboard['id'] . "'>" . $lboard['title'] . "</option>";
}
}
$verifystring = '$human_verify';
$kh_optionsgroup = $kh_optionsgroup . "</select>";
At the end of your query, you need to set an order, like so:
$groupsql="SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first=true;
foreach($group_ids as $value){
if(!$first){
$groupsql = $groupsql." OR ";
}else{
$first = false;
}
$groupsql = $groupsql." id = '".$value."' ORDER BY groupid ASC";
}
ORDER BY id ASC
This will make the query return its results in ascending order from the groupid column. Simply change ASC to DESC if you want it to go descendinng (high->low).

Categories