1

I started writing code for a basic voting system. But I got this error message.

Warning: mysqli_query() expects parameter 1 to be mysqli, bool given in E:\My-WORLD\xampp\htdocs\php-tut\voting\vote.des.php on line 6

<?php
  $con = mysqli_connect("localhost","root","","voting") || die("not 
 connected");
echo "connected";

if(isset($_POST['ele'])){

   global $con;

   $vote_ele = "update votes set ele = ele + 1";
   $run = mysqli_query($con,$vote_ele);

   if($run){
      echo "voted to electronics";
   }
   else{
      echo mysqli_error($run);
   }

  }
 ?>
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
srinu alla
  • 11
  • 4

2 Answers2

0

Neither || or or should be ever written in connection to any mysqli function.

How to properly connect with mysqli:

$host = '127.0.0.1';
$db   = 'voting';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $con = mysqli_connect($host, $user, $pass, $db);
    mysqli_set_charset($con, $charset);
} catch (\mysqli_sql_exception $e) {
     throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}

Given this script is not the only one uses a mysql connection, store this code in a separate file named mysqli.php and then include it in other files. Therefore your current code will become

<?php
include 'mysqli.php';
if(isset($_POST['ele']))
{
   $vote_ele = "update votes set ele = ele + 1";
   $run = mysqli_query($con,$vote_ele);
   echo "voted to electronics";
}

See - it is concise, tidy and reusable.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-2

When you use $con = mysqli_connect("localhost","root","","voting") || die("not connected"); you are assigning a bool to $con variable. So it is not mysqli anymore.

Also, When you use global $con you are overriding $con value, So it is not mysqli which you assigned in the pervious line anymore.

try this:

        $con = mysqli_connect("localhost", "root", "", "voting");

        if (mysqli_connect_errno())
            die("Failed to connect to MySQL: " . mysqli_connect_error());

        echo "connected";

        if (isset($_POST['ele'])) {

            // This will override $con value!!
            // global $con;

            $vote_ele = "update votes set ele = ele + 1";
            $run = mysqli_query($con, $vote_ele);

            if ($run) {
                echo "voted to electronics";
            }
            else {
                echo mysqli_error($run);
            }

        }
Hamed Ghasempour
  • 435
  • 3
  • 12