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 :)
Related
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.
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());
Been very frustrating but mysql is returning an empty set for this code (not echoing exists) :
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("repository", $con);
$url = stripslashes($url);
$url = mysql_real_escape_string($url, $con);
$exists = mysql_query("SELECT url FROM sites WHERE url = '$url' LIMIT 1");
if (mysql_num_rows($exists) == 1) {
echo "exists";
}
it should not be doing this because I've tested a good amount.
The table consists of one column "url", it is datatype varchar(1000) (the maximum). the url stored for test purposes is http://en.wikipedia.org/wiki/Thailand
Here's what you do as a first step. Remove the WHERE url = '$url' from your query altogether and print out mysql_num_rows($exists) before using it.
That should be enough to tell if it's one of the two likeliest problems:
bad URL resulting in no rows being returned; or
bad row caused by database containing other than you expect.
Based on your comments to date, the former is the most likely. If it turns out you get a row back without the where clause, you'll have to figure out why your URL is incorrect. This may be a case-sensitivity issue or a padding (size) issue, among other things.
If, as you mention in a comment, like works where = doesn't, then we need to see your data.
Execute (at the DB level):
select concat('[',url,']') from sites
and show us exactly what the output is. Similarly, output the URL being used by the code with something like:
print_r($url)
immediately before executing the mysql_query.
Please append the output from both those commands to your question.
I do not have experience in PHP programming but should not it be "SELECT url FROM sites WHERE url ='". $url."' LIMIT 1"
Please ignore this if $url works inside quotes (" ")
That will only check if MySQL only returned exactly one row. Check for
if (mysql_num_rows($exists) > 0)
assuming there is such data you're checking for, of course. You might want to broaden the search using LIKE and wildcards if you aren't absolutely sure the URLs you're passing are identical.
I'm having problems debugging a failing mysql 5.1 insert under PHP 5.3.4. I can't seem to see anything in the mysql error log or php error logs.
Based on a Yahoo presentation on efficient pagination, I was adding order numbers to posters on my site (order rank, not order sales).
I wrote a quick test app and asked it to create the order numbers on one category. There are 32,233 rows in that category and each and very time I run it I get 23,304 rows updated. Each and every time. I've increased memory usage, I've put ini setting in the script, I've run it from the PHP CLI and PHP-FPM. Each time it doesn't get past 23,304 rows updated.
Here's my script, which I've added massive timeouts to.
include 'common.inc'; //database connection stuff
ini_set("memory_limit","300M");
ini_set("max_execution_time","3600");
ini_set('mysql.connect_timeout','3600');
ini_set('mysql.trace_mode','On');
ini_set('max_input_time','3600');
$sql1="SELECT apcatnum FROM poster_categories_inno LIMIT 1";
$result1 = mysql_query($sql1);
while ($cats = mysql_fetch_array ($result1)) {
$sql2="SELECT poster_data_inno.apnumber,poster_data_inno.aptitle FROM poster_prodcat_inno, poster_data_inno WHERE poster_prodcat_inno.apcatnum ='$cats[apcatnum]' AND poster_data_inno.apnumber = poster_prodcat_inno.apnumber ORDER BY aptitle ASC";
$result2 = mysql_query($sql2);
$ordernum=1;
while ($order = mysql_fetch_array ($result2)) {
$sql3="UPDATE poster_prodcat_inno SET catorder='$ordernum' WHERE apnumber='$order[apnumber]' AND apcatnum='$cats[apcatnum]'";
$result3 = mysql_query($sql3);
$ordernum++;
} // end of 2nd while
}
I'm at a head-scratching loss. Just did a test on a smaller category and only 13,199 out of 17,662 rows were updated. For the two experiments only 72-74% of the rows are getting updated.
I'd say your problem lies with your 2nd query. Have you done an EXPLAIN on it? Because of the ORDER BY clause a filesort will be required. If you don't have appropriate indices that can slow things down further. Try this syntax and sub in a valid integer for your apcatnum variable during testing.
SELECT d.apnumber, d.aptitle
FROM poster_prodcat_inno p JOIN poster_data_inno d
ON poster_data_inno.apnumber = poster_prodcat_inno.apnumber
WHERE p.apcatnum ='{$cats['apcatnum']}'
ORDER BY aptitle ASC;
Secondly, since catorder is just an integer version of the combination of apcatnum and aptitle, it's a denormalization for convenience sake. This isn't necessarily bad, but it does mean that you have to update it every time you add a new title or category. Perhaps it might be better to partition your poster_prodcat_inno table by apcatnum and just do the JOIN with poster_data_inno when you need the actually need the catorder.
Please escape your query input, even if it does come from your own database (quotes and other characters will get you every time). Your SQL statement is incorrect because you're not using the variables correctly, please use hints, such as:
while ($order = mysql_fetch_array($result2)) {
$order = array_filter($order, 'mysql_real_escape_string');
$sql3 = "UPDATE poster_prodcat_inno SET catorder='$ordernum' WHERE apnumber='{$order['apnumber']}' AND apcatnum='{$cats['apcatnum']}'";
}
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.