-2

I am trying to make an ajax call, passing as parameter an integer 'mySensor'. The php file of the call contains the following code:

<?php

 $con = mysql_connect(...) or die('connection not made');
 $db = mysql_select_db('...', $con) or die('db not selected');

 $mySensor = mysql_escape_string($_POST["mySensor"]);
 $query = "SELECT Unit FROM sensors WHERE SensorID = ".$mySensor;
 $result = mysql_query($query, $con) or die('query not made');

 echo $result;

?>

So, from the table sensors I want to get the Unit (which is a string) of the element with SensorID=mySensor (there is only one such element). Echoing the $result doesn't work. How do I return that unit (which is, again, a string) back to my js script?

Thanks!

Kypros
  • 2,997
  • 5
  • 21
  • 27
  • Are you using any libraries (e.g., jQuery, Mootools), or just vanilla javascript? – emsoff Oct 29 '14 at 22:35
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** (`mysql_escape_string` has never been sufficient) that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Oct 29 '14 at 22:37
  • @jboneca, he's asking about how to do server-side stuff. – Jonathan M Oct 29 '14 at 22:38
  • @JonathanM Mhmm, and then he mentions how to return and presumably use this within the context of JavaScript. Echoing within a php script is not enough to "return that unit" through ajax. – emsoff Oct 29 '14 at 22:40
  • @jboneca, ok. I don't think he's asking about his client side stuff. If you think so, ok. – Jonathan M Oct 29 '14 at 22:44

1 Answers1

0

You still need to fetch the results of that query ie:

$result = mysql_query($query, $con) or die('query not made');
$array = mysql_fetch_assoc($result);
echo $array['Unit'];

Another thing is that mysql_escape_string(), where unless you are already declaring a function with that name, then it is not the actual mysql_real_escape_string library function

 $mySensor = mysql_real_escape_string($_POST["mySensor"]);

Important: You are using an obsolete database API and should use a modern replacement. You are also vulnerable to SQL injection attacks (mysql_escape_string has never been sufficient) that a modern API would make it easier to defend yourself from

Community
  • 1
  • 1
Kypros
  • 2,997
  • 5
  • 21
  • 27