Hi,
I am using this code but it is not working properly (another version of it is working but not this one!?) The only difference I can see between this code and the other one is the table name here is “TABLE 1” with a space in between (the default name when importing a CSV file). I have tried writing TABLE_1 and ‘table 1’ but it still does not work. Is there another error here? Or can you think why another piece of coding SELECTing different data from a different table in a different database is working. If I need to change the table name without a space how do I do that in PHPMyAdmin?
<?php
$conn = mysql_connect('localhost','xxxxxx','xxxxxx') or die ("could not connect");
if(preg_match('#^[a-z]{1}$#i', $_GET['letter'])) {
$letter = strtolower($_GET['letter']); // valid input
}else{
$letter = 'a'; // default value for invalid input
}
echo $letter;
$select_db = mysql_select_db('guitar4') or die ("could not load");
$a = "SELECT title, item FROM table 1 WHERE title LIKE '{$letter}%'";
$b = mysql_query($a);
echo "<ul>";
while($row = mysql_fetch_array($b))
{
echo "<li><a href=\\"$row[item]\\">$row[title]</a></li>";
}
echo "</ul>";
?>
Table names can not have a space. Your query is really saying “…FROM table AS 1…” It’s trying to query a table named “table” not “table 1”.
Please be aware that the mysql_* extension is now deprecated as of the current version of PHP and will very likely be removed from the next 5.x version and will likely not be in PHP 6.x (when it eventually is released). You should migrate over to either the mysqli_* extension or to PDO. PDO is a better choice as it doesn’t tie you down so much to a particular database server software.
Once you have migrated you should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle.
I’ve change the table name - now it is working.
The syntax is OK except that you cannot alias digits. So:
SELECT * FROM table 1
is the same with
SELECT * FROM table AS 1
BUT the problem is that you cannot set 1 as alias.
The solution of the initial issue is
SELECT * FROM `table 1`
Adding space (or other special characters) into variables, table names, file names, folder names (and any kind of names that are used into programming) is a very bad practice.
You can use _ (underline) instead and, in some cases, also ‘-’ (I only use _ and camel case)