AJAX call to a PHP/MySQL script failes if a dynamic table name has a space in it.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ArizonaJohn
    New Member
    • May 2009
    • 21

    AJAX call to a PHP/MySQL script failes if a dynamic table name has a space in it.

    Hello,

    Below I have some Ajax and the page it points to. This code works great if $_SESSION['find'] has no spaces in it (for example, if it is "elpaso"). However, if $_SESSION['find'] has a space in it (for example, "el paso"), then the Ajax fails.

    What can I do to make this Ajax work when $_SESSION['find'] has a space in it?

    Thanks.

    Ajax:
    Code:
    <?php
    
    
    ob_start();
    session_start();
    $find = strip_tags($_POST['find']);
    $find = trim ($find);
    $find = strtolower($find);
    $_SESSION['find'] = $find;
    ?>
    
    $.ajax({
    			type: "POST",
    			data: "action=vote_up&id="+$(this).attr("id"),
    			url: "votes12.php",
    			success: function(msg)
    			{
    				$("span#votes_count"+the_id).html(msg);
    				//fadein the vote count
    				$("span#votes_count"+the_id).fadeIn();
    				//remove the spinner
    				$("span#button"+the_id).remove();
    			}
    		});

    Then, on votes12.php:
    Code:
    <?php
    session_start();
    ?>
    
    <?php
    mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
    mysql_select_db("database") or die(mysql_error());
    
    function getAllVotes($id)
    	{
    	/**
    	Returns an array whose first element is votes_up and the second one is votes_down
    	**/
    	$votes = array();
    	$q = "SELECT * FROM {$_SESSION['find']} WHERE id = $id";
    	$r = mysql_query($q);
    	if(mysql_num_rows($r)==1)//id found in the table
    		{
    		$row = mysql_fetch_assoc($r);
    		$votes[0] = $row['votes_up'];
    		$votes[1] = $row['votes_down'];
    		}
    	return $votes;
    	}
    ?>
  • ArizonaJohn
    New Member
    • May 2009
    • 21

    #2
    Someone else told me to put backticks around the session variable and it solved the problem, so

    $q = "SELECT * FROM `{$_SESSION['find']}` WHERE id = $id";

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      #3
      Yep, that would do it.

      MySQL doesn't allow table/database/procedure names with spaces, or other special characters, unless you enclose them in back-ticks.

      Anyways, glad you found a solution, and thanks for sharing it!

      P.S.
      I change the title of the thread to reflect the actual problem... might make it easier for somebody suffering the same problem to find an answer ;)

      Comment

      Working...