0

Tried to make a simple click counter, doesnt work. Whats wrong with my trash code?

addLike.php

 <?php

$requestLikes = "SELECT Likes FROM test1";
$Likes = mysql_query($requestLikes);

$insertToLikes = "INSERT INTO test1 (Likes) VALUES (" . $Likes + 1 . ")";
mysql_query($insertToLikes);
$Likes = mysql_query($requestLikes);

?>

HTML

    <button action="/DEMO/PHP/addLike.php" method="post">Yeet
    </button>0

    <?php 
    echo '<h1>' . $Likes . '</h1>'; 
    ?>

Result Result

www.mySite/DEMO/PHP/addLike.php

Fatal error: Uncaught Error: Call to undefined function mysql_query() in /storage/ssd4/786/4680786/public_html/DEMO/PHP/addLike.php:4 Stack trace: #0 {main} thrown in /storage/ssd4/786/4680786/public_html/DEMO/PHP/addLike.php on line 4

and yes i have established a connection to the database EDIT: Dont mind the random "0" after the button tag

Jaypaque
  • 59
  • 8
  • `$Likes` is assigned to the result of `mysql_query`, which [returns an object](http://php.net/mysql_query). Then you do `$Likes + 1`, but `$Likes` is not a number so you can't add 1 to it. – Al.G. Feb 24 '18 at 16:42

1 Answers1

3
 <?php
$conn = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

$requestLikes = "SELECT Likes FROM test1";
$LikesQ = mysqli_query($conn, $requestLikes);
$Likes = mysqli_fetch_array($LikesQ);
$x = $Likes[0] + 1;
$insertToLikes = "INSERT INTO test1 (Likes) VALUES ('$x')";
mysqli_query($conn, $insertToLikes);
$y = mysqli_query($conn, $requestLikes);
$output = mysqli_fetch_array($y);
echo "<h1>$output[0]</h1>";

?>

Use MYSQLI please

$insertToLikes = "INSERT INTO test1 (Likes) VALUES (" . $Likes + 1 . ")";

You are vulnerable to MySQL injection, always use prepared statements or mysqli_real_escape_string

Richard
  • 325
  • 7
  • 23
  • 2
    This. mysql_ was deprecated due to it being insecure, mysqli_ is a speedier and more secure version that functions in a very similar way (to explain why **Use MYSQLI please**) – Phil Feb 24 '18 at 16:45
  • 1
    You should stick to Prepared Statements. Even `mysqli_real_escape_string()` has some security issues in certain situations. https://stackoverflow.com/questions/2353666/php-is-mysql-real-escape-string-sufficient-for-cleaning-user-input – M. Eriksson Feb 24 '18 at 16:54
  • Now allow me a one more question. is mysqli_fetch_array somehow related to php arrays? – Jaypaque Feb 24 '18 at 17:10
  • @Jaypaque yes it brings the array, for example `$test = mysqli_query($conn, "SELECT a,b,c")` and when you use `$array = mysqli_fetch_array($test)` you get the array. this can be displayed like this `echo $array[1]` or `echo $array['b']` both gives you **b** – Richard Feb 24 '18 at 17:12
  • Getting "mysqli_fetch_array() expects parameter 1 to be mysqli_result" error and have no idea what it wants of me – Jaypaque Feb 24 '18 at 20:35
  • @Jaypaque have you set up connection properly? are your queries the right syntax? test them in mysql database to double check – Richard Feb 24 '18 at 21:09