-2

I'm trying to assign the value of $data['id'] to a variable like this:

$totalfor = $data['id'];

but this is not working, the value is not passing to $totalfor

If i echo $data['id'], it gives the right value which is 85

i need the value of $data['id'] to use it into a Select query

Anyone know the correct syntax to achieve this ? Thanks

Here is the code:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";  

$jury = get_active_user('accountname'); 
$totalfor =  $data['id'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT total AS total FROM votestepone WHERE votefor = '$totalfor' AND votedby= '$jury'";
$result = $conn->query($sql);                       
if ($result = mysqli_query($conn, $sql)) {
    while ($row = mysqli_fetch_assoc($result)) {
        $totalvote = $row["total"];
    }
} else {
    echo "0 results";
}

?>

<?php echo $totalvote; ?>

The error is : Undefined variable: totalvote

If i set $totalfor = 85; --> it works but i need to use the value coming from $data['id'];

I'm in a view page and $data['id'] is coming from:

$data = $this->view_data;

if I <?php echo $data['id']; ?> it show 85

Tim Morton
  • 2,614
  • 1
  • 15
  • 23
Eroll
  • 11
  • 2
  • 2
    This is correct syntax. And it works: https://3v4l.org/SJaGN. And what is __not__ working in your code noone will guess. – u_mulder Mar 09 '19 at 18:09
  • Try showing us the code that successfully echoes $data[“I’d”] and also shows $totalfor not assigned. – Tim Morton Mar 09 '19 at 18:21
  • To get help faster, we need your code. Post all your code – Nancy Moore Mar 09 '19 at 18:33
  • 2
    where $data['id'] come from in your code ? Does it work if you put $data['id'] in place of $totalfor inside your query ? – Soren Mar 09 '19 at 18:35
  • You say if you change that last line to `echo $data['id'];` it shows 85? –  Mar 09 '19 at 18:38
  • 1
    If you are showing us the top of your file, `$data['id']` shouldn't be defined, unless this file is included somewhere. –  Mar 09 '19 at 18:39
  • Also, you are vulnerable to [SQL Injection](https://stackoverflow.com/questions/601300/what-is-sql-injection) –  Mar 09 '19 at 18:43
  • question is updated – Eroll Mar 09 '19 at 18:55

1 Answers1

0

mysqli_query returns false when there is an error not if there are no results. The error says $totalvote is undefined, not $totalfor so the query didn't find a single result.

var_dump($sql) and make sure the query is correct and it really does fetch a result row when run against your database.

blahy
  • 1,294
  • 1
  • 8
  • 9
  • Thanks @blahy and to all of you to put me on the right way. My mistake was focusing on the table votestepone that do not have the required informations. So i add a query to another table first and then the rest of the code works well. – Eroll Mar 11 '19 at 13:14