PHP echo of SQL query - php

I've a problem with my code. I can't wrap my head around what's wrong with the code or where I fail.
I basically want to calculate the average of multiple numbers from my database from one column.
/*data calculation*/
$calculation = "SELECT AVG(current) FROM offset_items";
$calculation_result = mysqli_query($connect, $calculation);
if($average = mysqli_fetch_assoc($calculation_result))
{echo "Average: ".$average["current"]."<br>";}
The problem here is, that I get only a blank displayed after the "Average: ".
But if I remove the AVG from the query, I get all results listed of that DB column. The DB contains data, which I import in the same script, as well as displaying them for testing.
I get the following error, which is the line of the echo:
Notice: Undefined index: current in C:\MAMP\htdocs\Offset_Items.php on line 50
I think the problem here is the mysqli_fetch_assoc, but I'm not sure.
Digging through the multiple topics about that "Undefined index" didn't solve my problem. Even when I declare the variable before as NULL.
I'm out of touch with programming, but currently picked it up again to code some tools for work. So if you guys could help me, I would be really thankful.

The PHP code that attempts to print the result reads:
$average = mysqli_fetch_assoc($calculation_result);
echo "Average: ".$average["current"]."<br>";
but the query that generates the result set does not contain any column named current.
Use an alias for the expression AVG(current) in the SELECT clause to get a column in the result set having the desired name:
SELECT AVG(current) AS current FROM offset_items

Related

PHP interprets Query Result as 0

I have come across a strange problem, which im trying to solve for quite some time now but can´t find any solution to this.
I am generating some lines with information which each of includes one checkbox. I have the following code in PHP which checks if a certrain entry exists, if so the checkbox is checked.
$sql = "SELECT COUNT(*) anz FROM jubilaeum WHERE jahr='".$Jahr."' AND mon='".$num."' AND AdrNr='".$RS1_row["AdrNr"]."' AND type='1'";
$rs_erledigt = $db->prepare($sql);
$rs_erledigt->execute();
$row = $rs_erledigt->fetch();
$anz = $row["anz"];
The Code generates me the following SQL Query:
SELECT COUNT(*) anz FROM jubilaeum WHERE jahr='2019' AND mon='5' AND AdrNr='14061' AND type='1'
PHPMyAdmin Query & Result
Now i am using a basic IF to check if there are any records found so i can check a checkbox
<input type="checkbox" name="mychk" id="mychk" value="somevalue" <?php if($anz>0) echo "checked"; ?> />
All checkboxes which have a proper entry in my DB are checked, except the very first one generated, i can swap the boxes around at free will, the first one never gets checked.
I tried to use the $row["Anz"] directly in my IF, didn´t fix the problem.
I think that PHP doesnt interpret the returned value of my query correctly, but i am clueless about how to fix this.
Did someone encounter similar problems and can help me with this?
Im new to posting in here, so please tell me if you need some more information.
Thanks in advance!
Edit: I just tried to change the Query from COUNT(*) to if(COUNT(*)>0,'ja','nein') while also changing the if to if($anz=="ja")
the value of $anz still remains empty.
I found the solution. My issue was a second fetch on my Query. After removing it, everything works fine.

Replacing content of block after generating clones using cloneBlock - PHPWord

Please can somebody be so kind to show me the syntax for using cloneblock in phpword.
So Ive got data in a MySQL DB, and for the single rows that I need to import into my word doc via phpword it works fine....to run my query and search and replace with template processor. BUT, now I want to insert multiple rows into my word document. I've researched and found that the cloneblock method is the answer. However I cannot get it working....currently my code runs but it doesn't seem to get to the second row.
I actually dnt get any error messages. My code executes fine...but the end display word file doesn't display fine....and if you see my code I got an echo statement...which echo's out in my browser exactly what I want "damaged" &"good", (as an example given of one of the row data) but that data doesn't get pulled into my word doc like that...it duplicates "damaged" , "damaged". .
$group_key=1;
do {   
//loop to increase my uuid  - ($repeatgroup')
$repeatgroup = $id."/"."trailer_repeat_group"."[".$group_key."]";
// query string
$trailer_repeat_grouping = mysqli_query($connect, "SELECT * FROM trailer_repeat_group LEFT JOIN main on trailer_repeat_group.PARENT_KEY = main.metainstanceID WHERE trailer_repeat_group.KEY_id = '$repeatgroup'");
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
while ($row1 = mysqli_fetch_array($trailer_repeat_grouping)) {   
//this echo below I am using to test exactly what happends – independent of
//PHPword/templateprocessor
echo $rttc =  $row1['right_trailer_tyre_condition'];
//inserting  / searching / inserting values
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
}
// ending of loop / checking loop
$group_key++;
} while ($group_key <= $trailer_count);
I've done investigation and found the solution.
You're cloning same blocks N times:
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
and then by doing fetch You're trying to replace right_trailer_tyre_condition with some value:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
Issue is that You're replacing all placeholders.
But in fact You need to replace them one by one with different values.
Solution is to define 3rd argument that means count of items to replace.
Simply change it to be:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc, 1);

Undefined index. database column name undefined

I've tried a lot of ways to execute this and it still says my column is undefined. I thought I didn't link it to my database correctly or something but even after searching for solutions here I still get the same error. I'm super newbie in coding especially in PHP and this problem had literally gone for days.
you are getting undefined for column because you have not check each of those with isset() or empty()
you should do like
$menuname = ( !empty($_POST['menu_Name']) )?mysqli_real_escape_string($query, $_POST['menu_Name']):'';
or
$menuname = ( isset($_POST['menu_Name']) )?mysqli_real_escape_string($query, $_POST['menu_Name']):'';
also looks your query is wrong.
it should be like
INSERT into mytable (mycolums) VALUES ('myvalues')
where
mytable is the name of table
mycolums can be name of one or more columns with comma saperated
and
myvalues can be value of each colums like 'col1val','col2val, ...
don't forgot to vote up if it helped you

Unable to subtract a table value via variable

I can not get an SQL update statement to subtract a variable from a table value. Here is my code:
$_SESSION_Job101=mysql_fetch_array(mysql_query("SELECT * FROM job_101 WHERE job_101.username='$_SESSION_User'"));
mysql_query("UPDATE characters SET currenergy=currenergy-$_SESSION_Job101['ecost'] WHERE username='$_SESSION_User'");
$_SESSION_Job101 is a perfectly valid result, as I pull from it on another page; I even pull the 'ecost' on said page. I also update currenergy this way in another script, except I use the number 1 instead of the variable. So I've narrowed it down to that variable.
It wouldn't matter that $_SESSION_Job101 is the result from a second table (job_101), and that query is updating to the table characters, would it?
We don't have enough information, but since you don't perform ANY error handling or validation that SQL resultset is returned, it could be an error caused by issues such as:
no rows returned in first query
some other parsing issue not directly evident
I would propose that you use temporary strings and echo the actual SQL queries.
Continue by actually testing them with MYSQL (through workbench, queryviewer, or console) in order to see where and what the error is.
Also, it's not recommended to skip error checking and try to combine so many lines/steps into 2 lines.
Imagine the first query does not return any results for example...
Debugging:
$query1 = "SELECT * FROM job_101 WHERE job_101.username='$_SESSION_User'";
echo $query1."<br/>";
$_SESSION_Job101=mysql_fetch_array(mysql_query($query1 ));
$query2 = "UPDATE characters SET currenergy=currenergy-$_SESSION_Job101['ecost'] WHERE username='$_SESSION_User'";
echo $query2."<br/>";
mysql_query($query2);
Update
Based on your comment I suggest you try the following two options:
1) Add a space between the - and $_SESSION_Job101['ecost'].
2) If that doesn't work, change your string to:
mysql_query("UPDATE characters SET currenergy=currenergy-".$_SESSION_Job101['ecost']." WHERE username='".$_SESSION_User."'";`

Problem with a SELECT WHERE query

Got a relatively simple MySQL query that I'm pulling using php with the following code:
$employeeNames = mysql_query(
"SELECT *
FROM employees
WHERE team=\"1st Level Technical Support_a\"
LIMIT 0,5000") or die(mysql_error());
$employeeNumRows = mysql_num_rows($employeeNames);
echo $employeeNumRows;
while ($row = mysql_fetch_array($employeeNames, $employeeNumRows)) {
echo $row['full_name'];
}
Now, if I run the query on the first line in SQL it gives me 18 results. If I echo $employeeNumRows it prints 18. Nothing else after that though.
If I change "1st Level Technical Support_a" to any other team in the table, it will bring up the proper results using PHP
This is the weirdest problem I've come across using MySQL/PHP - can anyone help? Has anyone seen something like this before?
Try removing the second parameter from your call to mysql_fetch_array, so that it reads mysql_feetch_array($employeeNames). See the documentation of the function to see how to use it properly.

Categories