$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
}
This is the structure of my code that I am trying to learn how to properly access... Here is my dilemma... I am trying to figure out how to explicitly find the associated count of nums dependent on the value of a Code.
Let me explain in better detail where my issue is....
Lets say the list of codes is
Code nums
1 624
7 825
571 450
9 393
2 739
9 590
The above code does successfully allow me to separate those values strictly into keys and values but I cannot figure out how to grab the nums value if the code is = to a certain value... I have currently been trying to declare a variable above the entire snippet of code and then declare it within the while statement but cannot figure out how to get the value to bind properly.... I will repaste the above code with one of my many failures in the while statement to give a better idea.
$Answer1 = 0;
$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
($Codes == 1){
$Answer1 = // Right Here I want to Get the value 624 related to Code 1... Dont want to embarass myself with examples of what I have tried...
}
So how do I make a condition to output the value associated with a Code? I want to explicitly define these values as the list of codes can change with each customer... Luckily there are only a certain amount of codes so its not like I need to define too many of them... I just want to make sure I can get the nums value associated with a code and display it.
Hope I did a good job explaining this. :)
I'd do:
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[$row['Code']] = $row['nums'];
}
and, to access the value associated to a code:
$code = 1;
$value = $values[$code];
Since they would share the same array key, something like this would work-
if ($Codes[$key] == 1){
$Answer1 = $Values[$key];
}
Related
hi i have a backend with php in cpanel and i have a problem with one of jsons . this is part of my php code :
...
}elseif ($work == "dollardate") {
$query3 = "SELECT * FROM tabl_dollar_date";
$result3 = $connect->prepare($query3);
$result3->execute();
$out3 = array();
while ($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {
$record3 = array();
$record3["dollar"] = $row3["dollar"];
$record3["date"] = $row3["date"];
array_push($out3, $record3);
}
echo json_encode($out3);
}
?>
this code show this in json :
[
{
"dollar":"15000",
"date":"1397-12-12"
}
]
how can remove array from json and show the json like this :
{
"dollar":"15000",
"date":"1397-12-12"
}
Easiest way (according his code):
change line
echo json_encode($out3);
to
echo json_encode($out3[0]);
One solution is that if you just want the latest value (in case there are multiple records in the table), then change the SELECT to order by date descending also set LIMIT to 1 to only get the 1 record anyway, and remove the loop to fetch the data and just fetch the 1 record...
$query3 = "SELECT `date`, `dollar`
FROM `tabl_dollar_date`
ORDER BY `date` desc
LIMIT 1";
$result3 = $connect->prepare($query3);
$result3->execute();
$row3 = $result3->fetch(PDO::FETCH_ASSOC);
echo json_encode($row3);
As you know which fields you want from the SELECT, it's good to just fetch those fields rather than always using *. This also means that as the result set only contains the fields your after, you can directly json_encode() the result set rather than extracting the fields from one array to another.
I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']
I have researched several related question in this forum and google, Kindly assist . I am trying to insert some values into database from several arrays stored in session. I also have some single values stored in some session also which i want to insert into multiple rows of dbase table.
//First, I recall the values stored in sessions from previous pages into the current page as below.
//take note of the comment in front of the sessions and All array contains the same number of values except for the first two sessions.
$ticketid="t".date('dmyHis').mt_rand (1000,9999);
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;//Not array, contains single value
$_SESSION['ticketid']=$ticketid;//Not array, Contains single value
$_SESSION['gamecode'];//array
$_SESSION['starttime'];//array
$_SESSION['optioncode']//array
$_SESSION['home'];//array
$_SESSION['away'];//array
$_SESSION['odd'];//array
Here, I connected to dbase. //Works fine.
require('gumodb.php');
Here i try to start a loop using one array session as key
foreach($_SESSION['starttime'] as $ro => $col){
mysql_query("INSERT INTO reg_bet (bettime, ticketid,matchcode,starttime,home,away,optionodd,optioncode) VALUES('$_SESSION[bettime]','$_SESSION[ticketid]','$_SESSION[gamecode]', '$_SESSION[starttime]','$_SESSION[home]','$_SESSION[away]','$_SESSION[odd]','$_SESSION[optioncode]' ) ")
or die(mysql_error());
}
It returns Notice: Array to string conversion in C:\xampp\htdocs\gumo\consel.php on line 61
EDIT QUESTION
I am trying to achieve something like this.
foreach($_SESSION['gamecode'] as $gc => $gcvalue && $_SESSION['starttime'] as $st =>$stvalue && $_SESSION['optioncode'] as $oc => $ocvalue ){
mysql_query("INSERT INTO reg_bet (matchcode,starttime,optioncode) VALUES('$gcvalue','$stvalue','$ocvalue') ")
or die(mysql_error()); }
$x = json_encode($_SESSION);
$query = "INSERT INTO ".$TABLE_NAME data "VALUES ("$x");";
$mysqli->query( $query );
Encode the session array into a single string and insert in to the table on a row of data.
When you fetch the same data use json_decode to convert the string into array.
Assuming the arrays in the $_SESSION variable are numeric, you could try something like this:
for ($i = 0; $i < $max_index_count; $i++) {
$query = "INSERT INTO ".$TABLE_NAME;
$query += "VALUES (".$_SESSION['index'][$i].");";
$mysqli->query( $query );
}
The above is pseudo code, but the problem is you are trying to use an array as a string. The $_SESSION variable is a multidemsional array, therefore, specify two ibdexes.
After so many trials, i was able to get it done with this
$ticketid="t".date('dmyHis').mt_rand (1000,9999);//ticket id generateed
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;
$_SESSION['ticketid']=$ticketid;
$_SESSION['gamecode'];
$_SESSION['starttime'];
$_SESSION['optioncode'];
$_SESSION['home'];
$_SESSION['away'];
$_SESSION['odd'];
require('gumodb.php');
foreach ($_SESSION['gamecode'] as $index => $value)
{
$ge = $_SESSION['gamecode'][$index];
$se = $_SESSION['starttime'][$index];
$oe = $_SESSION['optioncode'][$index];
$he = $_SESSION['home'][$index];
$ay = $_SESSION['away'][$index];
$od = $_SESSION['odd'][$index];
This post the arrays and non array into table row and display
mysql_query("INSERT INTO reg_bet (matchcode,ticketid,bettime,starttime,home,away,optionodd,optioncode) VALUES('$ge','$ticketid','$bettime','$se','$he' ,'$ay','$od' ,'$oe' ) ")
or die(mysql_error());
echo $_SESSION['gamecode'][$index] .'-'. $_SESSION['starttime'][$index].'- '. $_SESSION['optioncode'][$index].' -'. $_SESSION['home'][$index].'- '. $_SESSION['away'][$index].'- '. $_SESSION['odd'][$index].$bettime.' -' .$ticketid.'</br>' ;
}
Thanks for your contributions.
i am confused about how to extract values from a query, and place them into specific variable, when i don't know before hand what the name of the value will be.
it might be easier to show you what i mean.
the images below are the returned values, grouped by heading i.e Total_responded, Percent_responded etc.
so the first row will have under the column Responce the value Poached with a Percent_responded of 16.66667.
however the next row will have under column Responce $scrambled with a Percent_responded of 83.333333
i now want to place each of these values into individual variables like:
$poached , $poachedPercentage, $scrambled, $scrambledPercentage etc
i attempted to do it below, but produced the wrong figures. this is also not a cost effective way to do it. so, i would really appricaite some advice on how to extract the values
$getPollResult = results();
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce = safe_output(round($row['RESPONCE']));
$percentage = safe_output(round($row['Percent_responded']));
if($responce = 'Poached')
{
$percentageOne = $percentage;
$poached = $responce;
}
if ($responce = 'Scrambled')
{
$percentageTwo = $percentage;
$scrambled = $responce;
}
// echo " $percentagePoached $percentageScrambled ";die();
}
Use
$responce = trim($row['RESPONCE']);
Instead Of
$responce = safe_output(round($row['RESPONCE']));
Also, Change in if condition = to ==.
you can use "variable variables" (PHP Docs) to achieve that:
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce_name = trim($row['RESPONCE']);
$percentage_name = $responce_name . "Percentage";
$percentage = safe_output(round($row['Percent_responded'])); //don't know what safe_output() does
$$percentage_name = $percentage; //notice the double "$" here
}
your PHP variables will then look like this:
$PoachedPercentage = 17;
$ScrambledPercentage = 83;
// and so on....
I've been pulling my hair out on this one all afternoon. Basically, I have a long table of values (stored in SQL) and I want to go through the entire table and count the number of times each value shows up. I've called the values "pid" integers.
The best way I thought of to do this was to create an array with the PIDs as the key of the array, and the number of times each PID has occured in the table as the value at that key. Then go through the entire list and either add the PID to the array if it didn't already exist, or increment the click value if it already exists. The goal is to then figure out which PID has the highest number of clicks.
It sounds straightforward, and it is! I think I must have an error in my syntax somewhere because everything seems right. This is my first time working with arrays in PHP so be nice :)
Thanks so much!
$tabulation = array();
while ($row = mysql_fetch_array($result)) {
$pid = $row[1];
//if this post isn't in the tabulation array, add it w a click value of 1
if ( !isset( $tabulation[$pid] ) ){ array_push( $tabulation[$pid], 1 ); }
//if this post is already in the tabulation array, incrment its click value by 1
else {
$t = $tabulation[$pid]; $t++; $tabulation[$pid] = $t;
}
}
$highestClicksValue = -1;
$highestClicksPID = -1;
foreach ($tabulation as $pid => $clicks){
if ($clicks > $highestClicksValue){ $highestClicksPID = $pid; }
printf("PID: ". $tabulation[$pid] . " clicks: " . $tabulation[$clicks] . "<br />");
}
I know you're looking for a PHP answer, but have you considered that this is what SQL is best at?
select pid,count(*)
from theTable
group by pid
order by count(*) desc
Just a thought...
Why are you using the array key and value as keys for $tabulation in the last foreach?
This should work...
$tabulation = array();
while ($row = mysql_fetch_array($result)) {
$pid = $row[1];
//if this post isn't in the tabulation array, add it w a click value of 1
if ( ! isset( $tabulation[$pid] ))
$tabulation[$pid] = 1;
//if this post is already in the tabulation array, incrment its click value by 1
else
$tabulation[$pid]++;
}
arsort($tabulation);
$highestClicksValue = reset($tabulation);
$highestClicksPID = key($tabulation);
foreach ($tabulation as $pid => $clicks){
print("PID: ". $pid . " clicks: " . $clicks . "<br />");
}