0

Using a few answers on here I have got row being added to MySQL upon a button press but the data is blank and so I can only assume the variables are not being passed.

I really don't know what I am doing wrong, any help would be greatly appreciated.

PHP

<? $sql = "SELECT itemname FROM items ORDER BY itemname ASC";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {

echo "<button onclick='javascript:ajaxCall(" . $row['id'] . ")'><span class='btn-text'>" . $row['itemname'] . "</span></button>";
}
?>

jQuery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ajaxCall(id){
  $.ajax({
    type: "POST",
    url: "additem.php",
    success: function(data){
    // callback function
}
});
return false;
}
</script>

additem.php

// Connect database. 
include("settings.php");
mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name);

$id = $_POST['id'];

$itemsearch = mysql_query("SELECT itemname, itemcategory, price, qty FROM presales WHERE id='$id'");
$itemsearchrest = mysql_num_rows($itemsearch);

$itemname = $itemsearchrest['itemname'];
$itemcategory = $itemsearchrest['itemcategory'];
$price = $itemsearchrest['price'];
$qty = $itemsearchrest['qty'];


$sql = "INSERT INTO presales (itemname, itemcategory, price, qty) VALUES('$itemname', '$itemcategory', '$price', '0')";
if(mysql_query($sql)){
 return "success!";
}
else {
return "failed!";
}

?>
DNorthfield
  • 3
  • 1
  • 3
  • 2
    Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). You will also want to [Prevent SQL Injection!](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Nov 19 '14 at 22:24
  • You're not passing any data via your AJAX call, so all you will get are blanks. – Jay Blanchard Nov 19 '14 at 22:25

1 Answers1

0

mysql_num_rows returns the number of rows. It's not an array. Use fetch_assoc or similiar.
See sample in the PHP documentation!
Also your AJAX call is missing the data:

$.ajax({
  type: "POST",
  url: "additem.php",
  data: {
    id: id
  }
});

Please switch to PDO or MySQLi. MySQLi will use the same function names but it is object orientated. PDO will name the functions slightly different but basically work the same way.

Community
  • 1
  • 1
Maru
  • 894
  • 1
  • 12
  • 29