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.
Related
I am running a very simple SELECT query in MySQL and it's not working.
SELECT string_name FROM table_name;
This is giving me required output. Like
This is string one.
This is string two.
This is string three.
and so on...
But if I am running a query like this
SELECT * FROM table_name WHERE string_name='This is string one'
It's not giving any output. I even tried TRIM function.
SELECT * FROM table_name WHERE TRIM(string_name)=TRIM('This is string one')
But it's still not giving any output.
Please suggest what I am missing here. Is it because of some formatting or am I doing any silly mistake. By the way, Strings are saved as VARCHAR in the database.
To reiterate from comments; sometimes "non-printing" control characters (like newlines) can make their way into data they were never intended to be a part of. You can test for this by checking CHAR_LENGTH of field values versus what you actually see. Obviously, on large amounts of data this can be difficult; but if you know of one problematic value already, you can use this method to confirm this is the problem on that row before attempting to identify the offending character.
Once this problem is confirmed, you can use queries with MySql's ASC() and substring functions to identify character codes until you find the character; it can be best to start from the end of the string and work back, as often the offending characters are at the end.
The character or characters identified in known problem rows are often the cause of other problem rows as well, so identifying the issue in one known row can actually help resolve all such problems.
Once the character code(s) are identified, queries like WHERE string_name LIKE CONCAT('%', CHAR(13), CHAR(10)) should work (in this case for traditional Windows newlines) to identify other similar problem rows. Obviously, adjust character codes and wildcards according to your circumstances.
If no row should ever have those characters anywhere, you should be able to clean up the data with an update like this:
UPDATE theTable SET theString = REPLACE(REPLACE(theString, CHAR(10), ''), CHAR(13), '') to remove the offending characters. Again, use the codes you've actually observed causing the problem; and you can convert them to spaces instead if circumstances are better handled that way, such as a newline between two words.
Have you tried using LIKE for debugging purposes?
SELECT * FROM table_name WHERE string_name LIKE 'This is string one'
/!\ Don't just switch from = to LIKE, read about why here
TLDR:
= is apparently 30x faster.
Use = wherever you can and LIKE wherever you must.
First of all, I must acknowledge the points made by #Uueerdo were actually the the main cause of this issue. Even I was somewhat sure that there are some hidden characters in the string causing all the issue but I was not sure how to find and fix that offending character.
Also, the approach suggested by #Uueerdo to check and replace the offending character using the ASCII code seems quite legit but as he himself mentioned that this process will take lot's of time and one have to manually check every string for that one offending character and then replace it.
Luckily after spending couple of hours on it, I came up with a much faster approach to fix the issue. For that, first of all I would like to share my use case.
My first query was for selecting all the strings from a database and printing the result on page.
$result = mysqli_query($conn, "SELECT * from table_name");
while($row = mysqli_fetch_array($result)){
$string_var = $row["string_name"];
echo $string_var;
echo "<br>";
}
The above code was working as expected and printing all the string_name from the table. Now, if I wanted to use the variable $string_var for another SELECT query in the same table, it was giving me 0 results.
$result = mysqli_query($conn, "SELECT * FROM table_name");
while($row = mysqli_fetch_array($result)){
$string_var = $row["string_name"];
echo "String Name : ".$string_var."";
$sec_result = ($conn, "SELECT * FROM table_name WHERE string_var='$string_name'");
if(mysqli_num_rows($sec_result) > 0){
echo "Has Results";
} else {
echo "No Results";
}
}
In this snippet, my second query $sec_result was always giving me No Results as output.
What I simply did to fix this issue.
$result = mysqli_query($conn, "SELECT * FROM table_name";
while ($row = mysqli_fetch_array($result)){
$string_var = $row["string_name"];
$row_id = $row["id"];
$update_row = mysqli_query($conn, "UPDATE table_name SET string_name='$string_var' WHERE id=$row_id");
}
This step updated all the strings from the table without any hidden/problem causing character.
I am not generalising this approach and I am not sure if this will work in every use case but it helped me fix my issue in less than a minute.
I request #Uueerdo and others with better understanding on this to post a more generic approach so that it can help others because I think many people who can't find a right approach in such conditions, end up using LIKE in place of = but that completely changes the core idea of the query.
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 :)
I currently have this table.
Names
Two fields, ID and Names. Example data would be 1 | Harry.
Now what i am planning on doing is that if someone enters in something like Henry in my form, it will search my database for a result that begins with "H" Then if their are multiple results, it will see if there are any results that are "He" if their isn't it will fallback to the previous result from "H".
The only thing i can think of doing is this,
$inputted_name = "Henry";
$query = mysql_query("SELECT `name` FROM `names`");
while($row = mysql_fetch_array($query)){
$stored_name = $row['name'];
if($stored_name[0] == $inputted_name[0]){
if($stored_name[1] == $inputted_name[1]){
$result = $stored_name;
break;
} else {
// continue looking but then return the first result that matched one letter?
}
}
}
Now i am sure this can't be the best way to do it. Would it be possible in a query? I'm just really not sure where to look for a sensible answer for this one.
change
mysql_query("SELECT name FROM names");
to
mysql_query("SELECT name FROM names WHERE NAME='".$inputted_name."'");
and check you have more than one answer.
Note this is a bad way to do it if your name comes from a non controlled source, such as a web page, as it would allow a SQL injection, and then you would need parameters, but for your example it would work.
Edit: Now I read your question again, yes, you would need parameters or escaping such as:
$name = mysql_real_escape_string($inputted_name);
mysql_query("SELECT `name` FROM `names` WHERE NAME='".$=name."'");
Also, don't try and do in code what the database can do easily (like search for characters). Your code is almost always going to be worse than the database for doing a search, leave it to the database.
My query below updates a record using variables to identify the data in the DB. I think my syntax is correct although it might be wrong. Also, I am absolutely sure that the variables have legitimate values in them. Why won't this query work?
UPDATE `databasename`.`".$tablename."` SET `stock` = '".$f."' WHERE `myerspark`.`item_id` ='".$g."' LIMIT 1
Thanks guys. Tom, yes I have tried that and it works fine. But it is frustrating because I echo all three variables at the end of the script and they all display legitimate values.
Hamish, how do I view these errors?
Jon_Darkstar, these variables are assigned in previous lines of code. Here is my entire code block:
//variables $f, $g, and $tablename assigned from POST variables in previous lines
mysql_select_db($database_Yoforia, $Yoforia);
mysql_query("UPDATE `yoforiainventory`.`".$tablename."` SET `stock` = '".$f."' WHERE `".$tablename."`.`item_id` ='".$g."' LIMIT 1 ");
mysql_close($Yoforia);
echo ($f);
echo ($tablename);
echo ($g);
Again, when i echo these variables, they all come out with good values.
I'm kind of confused what belongs to SQL, what belongs to PHP, where that string comes from, etc. What you have might be fine (if there is a double quote in front and end that i dont see.
I'd probably write it like this:
$sql = "UPDATE databasename.$tablename SET stock = '$f' WHERE myerspark.item_id = '$g' LIMIT 1"
$res = mysql_query($sql, $conn).....
you can backtick more stuff (and/or do mysql_real_escape) for 'extra safety;, but that covers the idea.
What is myerspark? i dont see how it relates to the query, that is probably you're real meaningful error, whether there is a syntax error or not. If myerspark is a seperate table from tablename then you've got an issue here, maybe a JOIN you ought to have?
I am trying to input multiple pieces of data through a form and all the data will be separated by (,). I plan to use this data to find the corresponding id for further processing through an sql query.
Below is the code I use.
$key_code = explode(",", $keyword);
//$key_count = count($key_code);
$list = "'". implode("','", $key_code) ."'";
//$row_count = '';
$sql4= "SELECT key_id FROM keyword WHERE key_code IN (".$list.")";
if(!$result4 = mysql_query($sql4, $connect)) {
mysql_close($connect);
$error = true;
}else{
//$i = 0;
while($row = mysql_fetch_array($result4)) {
$keyword_id[] = $row['key_id'];
//$i++;
}
//return $keyword_id;
}
The problem i see is that keyword_id[0] is the only element that contains any data (the data is accurate). Even if I input multiple values through the aforementioned form.
I thought it might be an error in the sql but I echo'ed it and it looks like:
SELECT key_id FROM keyword WHERE key_code IN ('WED','WATER','WASTE')
The values in the brackets are exactly what I inputted.
I even tried to figure out how many rows are being returned by the query and it shows only 1. I assume something is wrong with my query but I cannot figure where.
Any help will be greatly appreciated.
Edit: Alright Solved the problem. Thanks to suggestions made I copied and pasted the $sql_query I had echo'ed on the website into mysql console; which resulted in only 1 row being retrieved. After taking a closer look I realized that there was a whitespace between ' and the second word. I believe the problem starts when I input the key_code as:
WED, WATER, WASTE
Instead inputting it as
WED,WATER,WASTE
fixes the problem. I think I should make it so that it works both ways though.
Anyway, thank you for the help.
I am pretty sure that the query is ok. How many rows do you get with just
SELECT key_id FROM keyword
I think that there is just one line that matches your WHERE.
Check the query directly in the database(with phpmyadmin, or in the mysql console), however this query seems to be working as you may assumed. If it returns only 1 row when you use it directly in the db, then maybe there is only one row in your table wich matches this query.