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

1
  • $Likes is assigned to the result of mysql_query, which returns an object. Then you do $Likes + 1, but $Likes is not a number so you can't add 1 to it. Commented Feb 24, 2018 at 16:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

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)
You should stick to Prepared Statements. Even mysqli_real_escape_string() has some security issues in certain situations. stackoverflow.com/questions/2353666/…
Now allow me a one more question. is mysqli_fetch_array somehow related to php arrays?
@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
Getting "mysqli_fetch_array() expects parameter 1 to be mysqli_result" error and have no idea what it wants of me
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.