David Broom
David Broom

Reputation: 3

Show/Hide a button based on SQL query result

Hi i'm trying to hide a button if the count of rows with a certain value id in this case DeckID are Greater than 40.

My code so far is as below:

$sql3 = "SELECT COUNT(*) FROM cards WHERE DeckID=$deck";
$result3 = $link->query($sql3) or die(mysql_error());
if(mysqli_fetch_assoc($result3) <= 40){
    ?> 
    <form action='includes/addtodeck.php' method='get'>
      <input type='hidden' name='un' value='<?php echo$row["id_unique"] ?>' />
      <button value='<?php echo $deck ?>' name='DID'>Add to deck</button>
    </form>
    <hr align='left' width='80%'>
    <?php
} else {
    echo "Deck is full <br><br>";
}

Any help is greatly appreciated.

Upvotes: 0

Views: 859

Answers (2)

Mr Hery
Mr Hery

Reputation: 870

It seem you mixed up your code. Here I give you full example to start up from connection until the form. (Using Procedural SQL connection with mysqli)

$conn = mysqli_connect("127.0.0.1", "username", "password", "database_name");

$deck = mysqli_real_escape_string($deck);   //Prevent SQL Injection at somepoint by escaping string
$q = mysqli_query($conn, "SELECT * FROM cards WHERE DeckID = '{$desk}'"); //Select you table
$row = mysqli_fetch_array($q); //Fetch as array or you may use fetch_assoc and fetch_object as well.

if(count($row) <= 40){ //other than count, you may use mysqli_num_rows($q)
?> 
    <form action='includes/addtodeck.php' method='get'>
        <input type='hidden' name='un' value='<?php echo $row["id_unique"] ?>'>
        <button value='<?php echo $deck ?>' name='DID'>Add to deck</button>
    </form>
    <hr align='left' width='80%'>
<?php
}else{
    echo"Deck is full <br><br>";
}

Like other said, the above code are not 100% secured on SQL injection, you might want to use Data Binding for best performance and secure.

As you can see, I remove the COUNT(*) because you want to use the $row["id_unique"] in your form, so have to select all/specific column rather than just count it.

Upvotes: 0

Shivrudra
Shivrudra

Reputation: 684

In this solution, I have not used SQL injection. But it will be great if you use SQL injection. I just mentioned solution to your code without SQL injection.

$sql3 = "SELECT COUNT(*) as count FROM movies";
$result3 = $link->query($sql3) or die(mysql_error());
$rows = mysqli_fetch_array($result3);
if($rows['count'] <= 40){
    echo "Deck is not full";
}else{
    echo"Deck is full <br><br>";
}

In above code, I have used alias(count) in SQL. mysqli_fetch_array($result3) this return data in array format. so you have to check values from array Ex. $row['count'].

Upvotes: 1

Related Questions