Issue retrieving SUM result from query - php

I have this query here which I use in order to get the sum of a certain column, however I keep getting the error Undefined index.
$sql_shuma="SELECT SUM(vlera) AS shuma "
."FROM servis_pjeset_perdorura "
."WHERE random = $random";
$resultshuma = odbc_exec($connection, $sql_shuma) or die(odbc_error());
while( $rowshuma = odbc_fetch_array($resultshuma) ) {
echo $total1 = $rowshuma['shuma'];
}
?>
What am I doing wrong here? Maybe it's the $total1 value, I don't know how to save the result.
Thanks

Is $random an integer? If not, you must use ' ' to delimit the string, like this:
$sql_shuma="SELECT SUM(vlera) AS shuma FROM servis_pjeset_perdorura WHERE random = '$random'";

Related

How can I append a string to an object property?

I am trying to send a response back to my front end with the amount of days in a customers billing period. I query this number but would like to append " Days" after it. So far I have:
<?php
require "../../inc/dbinfo.inc";
$projectnum =$_POST['projectnum'];
$sql = $conn->prepare("SELECT (SELECT TermsofPayment FROM tblCustomers WHERE CUSTOMERID = ProjectCustomer) AS NetTerms FROM tblProjects WHERE PROJECTNOID = ?");
if($sql){
$sql->bind_param("i", $projectnum);
$sql->execute();
$hold = $sql->get_result();
$obj = $hold->fetch_assoc();
$addOn = " Days";
$obj->NetTerms = $obj->{'NetTerms'. $addOn};
echo json_encode($obj);
}
$sql->close();
exit();
?>
After trial and error it appears as though the second last line has no effect on the result. I've looked through the web to find no solutions to this (maybe my search didn't contain the right keywords).
Current Response: {"NetTerms":30}
Desired Response: {"NetTerms":30 Days}
You have/had two problems there:
1st you wanted to concatenate a variable to another one and had a wrong syntax.
$addOn = " Days";
$obj->NetTerms = $obj->{'NetTerms' .$addOn};
// this would try to get a value of `$obj->NetTerms Days`, which doesn't exist.
should have been
$obj->NetTerms = $obj->NetTerms . $addOn;
// or
$obj->NetTerms .= $addOn;
All of this threw an error, because $obj is an array (as return from fetch_assoc()), not an object.
So treat it as an array and it should work:
$obj['NetTerms'] = $obj['NetTerms'] . $addon;

How to access an Arrays value by the value of another array

$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];
}

Simple mysqli query not returning anything

I am almost certain that this is a boneheaded question with a very simple answer, but I've been knocking my brain against the desk for the last 30 minutes or so and figured it was time to ask for help.
I need to fetch the current highest existing keyID in the database. Simple! So I did this:
$newIDQ = "SELECT MAX(mediaKey) FROM `imd_media`";
$newIDResult = $con->query($newIDQ);
$row = mysqli_fetch_array($newIDResult);
echo "Highest ID should be: " . $row['mediaKey'];
But it never spits anything out in $row['mediaKey']. It's been awhile since I used mySQL for anything and this is my first tussle with mysqli, so I'm sure I'm just looking right past the answer or misunderstanding something.
$row[0] will do it I believe.
Always debug your code. Say, for your current problem print_r($row); can help
Try this:
$newIDQ = "SELECT MAX(mediaKey) AS mediaKey FROM `imd_media`"; // rename the result col
$newIDResult = $con->query($newIDQ);
$row = mysqli_fetch_array($newIDResult);
echo "Highest ID should be: " . $row['mediaKey'];
or this:
$newIDQ = "SELECT MAX(mediaKey) FROM `imd_media`";
$newIDResult = $con->query($newIDQ);
$row = mysqli_fetch_array($newIDResult);
echo "Highest ID should be: " . $row['MAX(mediaKey)']; // your probable current result
$newIDQ = "SELECT MAX(mediaKey) FROM 'imd_media'";
$newIDResult = $con->query($newIDQ);
$row = $newIDResult ->fetch_array(MYSQLI_ASSOC);
echo "Highest ID should be: " . $row['mediaKey'];`

PHP/MySQL Count() Issue

I am trying to create a class registration system for a client that utilizes PHP and MySQL. I have the database and table all set up and that part works just fine, however, the client has requested that upon registration, if there are 3 or fewer students enrolled to warn that the class may not run.
I'm trying to use the count() function as well as passing a dynamic variable from a cookie, set from the registration PHP script. However, I've hit a roadblock. I can't seem to get the count() function to actually count the rows. My select statement is below. Any help would be greatly appreciated.
$class = $_COOKIE["class"];
$min_check = "SELECT class_list, COUNT(class_list) as count
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING count < 20";
$result = mysql_query($min_check);
$count = mysql_num_rows($result);
if ($count < 4)
{
echo "IF THERE ARE 3 OR FEWER PEOPLE SIGNED UP FOR THIS CLASS, IT MAY NOT RUN.\n";
echo "THERE ARE CURRENTLY " . $count . " PEOPLE SIGNED UP.\n";
}
else if ($count > 4)
{
echo "There are currently " . $count . " people signed up for this class.";
}
?>
Your SQL query is returning a list of the class_list values, along with a count of each specific instance, where there are less than 20 people registered.
$count = mysql_num_rows($result);
...is getting the number of records returned in the resultset, not the alias count value, which is why you aren't seeing the output you expect. You need to read into your resultset to get the value:
while ($row = mysql_fetch_assoc($result)) {
$count = $row['count'];
if($count < 4) { ... }
}
The count that you want is returned in the row of the query. the mysql_num_rows will count the rows returned, which is not what you want. Use this instead.
$result = mysql_query($min_check);
$count = mysql_fetch_row($result);
$count = $count[0];
On a first glance, the HAVING count < 20 is unnecessary.
You use the MySQL-count-function, but never retrieve it's value!? Use:
$firstRow = mysql_fetch_row($result);
$count = $firstRow[1]; // 1 indicates the second column (0 being the first)
I don't recommend using known MySQL identifiers like count. It's confusing.
$class = mysql_real_escape_string($_COOKIE["class"]);
$min_check = "SELECT class_list, COUNT(class_list) as mycount
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING mycount < 20";
Don't forget to escape the contents of that cookie!
The error is that count is a reserved word. You need to either surround it in backticks `count` or even better, use a different moniker. It's not an error per se, but it's just too confusing.
Next up, you are not actually retrieving the mycount result from the database. I suggest using code something like this:
$result = mysql_query($min_check);
while( $row = mysql_fetch_assoc($result) ) {
$people_count = $row['mycount'];
if ($people_count < 4) { echo "this" }
else { echo "that" }
}

Sql query only printing first row

I am coding in php and the code takes data from an array to fetch additional data from a mysql db. Because I need data from two different tables, I use nested while loops. But the code below always only prints out (echo "a: " . $data3[2]; or echo "b: " . $data3[2];) one time:
foreach($stuff as $key)
{
$query3 = "SELECT * FROM foobar WHERE id='$key'";
$result3 = MySQL_query($query3, $link_id);
while ($data3 = mysql_fetch_array($result3))
{
$query4 = "SELECT * FROM foobar_img WHERE id='$data3[0]'";
$result4 = MySQL_query($query4, $link_id);
while ($data4 = mysql_fetch_array($result4))
{
$x += 1;
if ($x % 3 == 0)
{
echo "a: " . $data3[2];
}
else
{
echo "b: " . $data3[2];
}
}
}
}
First and foremost, improve your SQL:
SELECT
img.*
FROM
foobar foo
INNER JOIN foobar_img img ON
foo.id = img.id
WHERE
foo.id = $key
You will only have to iterate through one array.
Also, it appears that you're actually only selecting one row, so spitting out one row is expected behavior.
Additionally, please prevent yourself from SQL injection by using mysql_real_escape_string():
$query3 = "SELECT * FROM foobar WHERE id='" .
mysql_real_escape_string($key) . "'";
Update: As Dan as intimated, please run this query in your MySQL console to get the result set back, so you know what you're playing with. When you limit the query to one ID, you're probably only pulling back one row. That being said, I have no idea how many $keys are in $stuff, but if it spins over once, then it will be one.
You may be better off iterating through $stuff and building out an IN clause for your SQL:
$key_array = "";
foreach($stuff as $key)
{
$key_array .= ",'" . mysql_real_escape_string($key) . "'";
}
$key_array = substr($key_array, 1);
...
WHERE foo.id IN ($key_array)
This will give you a result set with your complete list back, instead of sending a bunch of SELECT queries to the DB. Be kind to your DB and please use set-based operations when possible. MySQL will appreciate it.
I will also point out that it appears as if you're using text primary keys. Integer, incremental keys work best as PK's, and I highly suggest you use them!
You should use a JOIN between these two tables. It the correct way to use SQL, and it will work much faster. Doing an extra query inside the loop is bad practice, like putting loop-invariant code inside a loop.

Categories