-1

The idea in this code is to print the amount of followers that an user has...

This is the code I've created

AJAX

$(document).ready(function() {
var usuario = $(".left h4").attr("data-id");
var seguidor = $("#user_account_info .profile_ball").attr("data-id");

$.ajax({
    type: "POST",
    url: "./include/php/followers.php",
    data: { user: usuario, follower: seguidor },
    success: function(data) { $(".right h4 i").html(data); }
});
return false;
});

PHP

<?php
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseña = "";

$conexion = new PDO($dsn, $usuario, $contraseña);
$resultado = null;

$user = $_POST["user"];
$seguidor = $_POST["follower"];

$sql = "SELECT count(*) as seguidores FROM seguidores WHERE id_canal = '$user'";

if(isset($resultado)){ $datos = $resultado->fetch(); }

$seguidores = $datos["seguidores"];

return $seguidores;
?>

I'm returning the result in the php file and taking back the data in the php one. I print in the div I want to display, but it shows me only an error:

Notice: Undefined variable: datos in C:\wamp\www\tapeHD\include\php\followers.php on line 16

Antonio
  • 99
  • 8
  • You're not checking your queries for errors and just assume that they work. You need to add some error checking to your queries. – Jay Blanchard Sep 01 '15 at 20:16
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Sep 01 '15 at 20:17
  • You never execute your query. You have multiple problems, not dissimilar to a question you asked earlier today. If you will follow some of the advice that folks have given you it would reduce the number of problems you're experiencing. – Jay Blanchard Sep 01 '15 at 20:19
  • Your `$resultado` is NULL so the fetch in the if-statement never gets executed, therefore `$datos` is undefined. – Victor Levin Sep 01 '15 at 20:19
  • 1
    note - `return $seguidores;` needs to be `echo $seguidores;` as `return` does not print out the value – Sean Sep 01 '15 at 20:21

2 Answers2

1

Looks like the problem is $datos is only set if $resultado is set. And nowehere in your script is the SQL query actually being executed. I would set a default value for $datos and execute your query.

SamA
  • 587
  • 3
  • 6
0

It looks like it could be because $resultado is null and therefore not set. So when the condition statement of if(isset($resultado)..... comes up, it's actually not executing and causing $datos to populate. Therefore $datos["seguidores"]; doesn't exist when you try to assign it to $seguidores.

tllewellyn
  • 903
  • 2
  • 7
  • 28