PHP interprets Query Result as 0 - php

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.

Related

Need mysql results even if all parameters are not met

I'm using my client's mysql database. My client has form search fields: voltage, power, size, material and length. They want the visitor to enter any combination of these and get some results. I've tried using AND and we get no results, I tried using OR and got all the records no matter what. What am I missing? The form data is turned into $POST_variables like $pvoltage. Any ideas on how to do this?
WHERE
(voltage = '$pvoltage' AND power_kw = '$ppower' AND size LIKE '$psize%' AND
material = '$pmat' AND immers_length LIKE '$plength%')
Also tried it with OR - gave me everything instead of just the results where there was data. This gives me nothing.
This finally worked for me in the WHERE statement:
IF('$pvoltage' ='',voltage LIKE '%',voltage LIKE '$pvoltage')

php weird issue when calling from web browser

I'm currently developing a video game, and experimenting a weird behavior trying to get the MAX value of a table in my database.
"select MAX(challengeID) AS challengeID from Challenges"
When I execute the sentence from phpMyAdmin all is going as expected, but when I call it from a web browser, I have to query twice in order to get the right answer. First time I call it from browser is returning the last MAX value before updating the table... maybe something related to cache¿
Edit:
There is all the PHP code (I think it is not a code issue, since it is the easiest query in the project...)
PHP code:
<?php
# connection stuff
$query = "select MAX(challengeID) AS challengeID from Challenges";
$result = mysql_query($query) or die('Query failed: ' .mysql_error());
$row = mysql_fetch_array($result);
echo $row['challengeID'];
?>
More info: I also tried this query with exactly the same issue
select challengeID from challenges group by challengeID order by challengeID desc
Thanks!
Carlos
So, I finally got the solution. Adding a hash code to the url is returning the correct value at the first call. The hash has to be different from the last hash used, but every two calls it is reseted ( I dont know why... I have to open a new question¿ ).
Thanks for your help! And #u_mulder take a tea please :)

no element found - SQL statement looks good though

Anyone see what is wrong with this line of code? using php/mysql
$sqlInsert="INSERT INTO sched_trades_proposed (id,originalDate,originalUserid,originalRot,original_sched_main_id,proposedDate,proposedUserid,proposedRot,proposed_sched_main_id,timeStampedProposal,randomHash) VALUES('','".$originalDate."',".$_SESSION[userid].",$originalRotation,$original_sched_main_id,'".$proposedDate."',$proposedRad,$proposedRotation,$proposed_sched_main_id,UNIX_TIMESTAMP(),'".$randomHash."')";
fire bug says "no element found" in jquery-1.8.2.js (line 7209, col 314) and points to this INSERT statement. I don’t see anything wrong with the insert statement. I realize fire bug isn't server side. I am still trying to solve the error though. If I comment out this line of code I get no error.
the surrounding code is:
$randomHash=sha1(rand(1,1000));
$sqlInsert="INSERT INTO sched_trades_proposed (id,originalDate,originalUserid,originalRot,original_sched_main_id,proposedDate,proposedUserid,proposedRot,proposed_sched_main_id,timeStampedProposal,randomHash) VALUES('','".$originalDate."',".$_SESSION[userid].",$originalRotation,$original_sched_main_id,'".$proposedDate."',$proposedRad,$proposedRotation,$proposed_sched_main_id,UNIX_TIMESTAMP(),'".$randomHash."')";
echo '<p>'.$sqlInsert;
$resultInsert=mysql_query($sqlInsert);
when I manually insert the INSERT statement into mySQL it gives no errors...But I am getting while trying through the web page?
Here is an example with data in the outputted INSERT statement which all looks good:
INSERT INTO sched_trades_proposed (id,originalDate,originalUserid,originalRot,original_sched_main_id,proposedDate,proposedUserid,proposedRot,proposed_sched_main_id,timeStampedProposal,randomHash) VALUES('','2013-01-10',10,7,710,'2013-01-14',3,19,723,UNIX_TIMESTAMP(),'f33f7ae89c2c6ab8e29a3cb0a97bb1f9456aacba')
FYI: the original id is auto incremented, so I insert a '' as the first column which is kosher.
Firebug says so because you echoed it to the client, and the client HTML parsing is confused because of that. Perhaps because that echo got into a wrong place? Remove that echo. Why do you need it? Or place that echo at a place which would not interfere with your HTML code. e.g. perhaps wrap a div/span around where that echo is?
The INSERT returns no data or acknowledgement by itself. If you are using jQuery to display the inserted data, you will need to run another SELECT to get it again. You can also just return the primary key of the inserted row(assuming MySql for the link although the same thing works with PDO). See this

mysql query does not work on different files -php

i might be doing some idiot mistake, but i could not figure that out. i have some values coming from html and wanna insert into mysql db. problem is, the very same query does not work in regular php file (that includes other queries), but when i try on an independent php file, it does. here is a sample of the code:
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15);
as i mentioned, the very same code works when i just copy this snippet to a new php file, and it works smoothly.. as you see, there are 20+ insert with the same php, because there are 25+ tables, but data is not much. first 14 query and following 7 queries do work by the way.
do you have any ideas?
There are some things to check and do.
Sanitize user input:
"('$article_id', '".mysql_real_escape_string($_POST['Article_Title'])."')";
You might also want to check if the value is what you expect.
Is your $article_id correct for column Article_ID?
Are your table and column names correct?
Check for errors:
$res = mysql_query($sql15);
if (!$res)
echo mysql_errno($link) . ": " . mysql_error($link);
Show us you complete query:
echo $sql15;
First of all i would suggest you to write your insert query like below
$sql15="insert into body SET Article_ID = '$article_id', Article_Title = '".$_POST['Article_Title']."'";
echo $sql15;
mysql_query($sql15);
so that each time when you add new column to database it would be easy for u to change insert query. echo your query and see it in browser. in it seems to o.k then copy it and paste it in SQL section under your phpmyadmin (see you are choosing proper database) and run it. if one row inserted successfully then your query is alright.
I hope this would help you a little.
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15) or die(mysql_error());
use like this u will be get the error. then u will be find the issue
I think using mysql_real_escape_string may solve your problem.I also recommend you to store your form data in a string.
$article_title= mysql_real_escape_string($_POST['Article_Title']);
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '$article_title') ";
mysql_query($sql15) or die(mysql_error());

UPDATE in mysql didn't work in my PHP page.

First of all I'm a rookie to Programming, I created a PHP page to update a value from my mysql(myadmin) database, but the value is not updating. I also tried to retrieve values from database it's working just fine but this UPDATE code is not working! I don't know why, please check out my code below.
$qs=mysql_query("update staff set review=$newrate where name=$rateuser");
$resu=mysql_query($qs);
All variables are double defined, assigned with proper values, checked and I tested variables using echo, table name is also checked, it's all fine, but I think the problem is with Update query, I searched internet for the syntax but it's not different than mine. Please help me out
How are $newrate and $rateuser set?
mysql_query("UPDATE staff SET review = '".mysql_real_escape_string($newrate)."' WHERE name = '".mysql_real_escape_string($rateuser) ."'");
http://php.net/manual/en/function.mysql-real-escape-string.php
Try:
$qs=mysql_query("update staff set review='$newrate' where name='$rateuser'");
Do not use second line.
You probably just need some " around your values $newrate and $rateuser
But if you did an echo, why not actually echo for us what the query-string becomes?
You need single quotes around string values on your query:
$qs=mysql_query("update staff set review='$newrate' where name='$rateuser'");
(assuming both variables are strings)

Categories