Show/Hide a button based on SQL query result - php

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.

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'].

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.

Related

How to fetch data form database using array

I am trying to fetch data from the database, but not retrieve data particular id.
this is my one page:
example1.php
<a style="color: #3498DB;" class="btn btn-default" href="http://www.example.com/getafreequote?id=<?php echo $row['product_id']; ?>">Get Quote</a>
example2.php
<?php
$id = isset($_GET['id'])?$_GET['id']:'';
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
while ($fetch1 = mysql_fetch_object($run1)){
?>
<div class="col-xs-12 col-sm-6">
<label for="GetListed_product"></label>
<input class="le-input" name="product" id="GetListed_product" type="text" value="<?php
$b = $fetch1->product_id;
$q2 ="SELECT product_id,name FROM oc_product_description WHERE product_id = $b";
$q3 = mysql_fetch_assoc(mysql_query($q2));
echo $q3['name'];
?>" >
<span id="productmsg" class="msg"></span>
</div>
<?php
}
?>
</div>
but didnot get data form particular product id. I have got error show like this
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in example.com/example2.php on line 71
Please don't use mysql functions they are deprecated. Use mysqli or PDO for database operations. Also the way you write the query string makes it easy for an SQL injection, use prepared statements instead. Here is an example:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch();
You can also use prepared statements for inserting or updating data. More examples here
As said by FilipNikolovski, don't use mysql functions they are deprecated. Use mysqli or PDO for database operations.
For your problem, the function mysql_query is returning false. The query is not returning any result and thus mysql_query is returning false.
Make a check like this:
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
if($run1)
{
if(mysql_num_rows($run1) > 0)
{
while ($fetch1 = mysql_fetch_object($run1))
{
// your stuff here
}
}
else
{
echo "No records found.";
}
}
else
{
echo "Error in query : ".mysql_error();
}
This will help you to detect the problem and to solve as well.

How to change the option text in php?

I tried to build an admin page. The admin will fill a form to add new product in the database and display it in the shop website. The problem is when I tried to select a gender from the dropbox, the new product doesn't add in the product table in the database as you can see below: (I want to select gender such as Boys)
The Admin Page and database result:
The code I used:
$host = "";
$userMS = "";
$passwordMS = "";
$connection = mysql_connect($host,$userMS,$passwordMS) or die("Couldn't connect:".mysql_error());
$database = "projectDataBase";
$db = mysql_select_db($database,$connection) or die("Couldn't select database");
if (isset($_POST['sAddProduct']))
{
addNewProduct();
}else if(isset($_POST['delete']))
{
$Product_ID=$_POST['Product_ID'];
$mysqlquery="delete from Product where Product_ID= ".$Product_ID."";
mysql_query($mysqlquery);
echo "Deleted successfully";
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}else{
showForm();
}
// add new product
function addNewProduct()
{
$ProductName = $_POST['Product_Name'];
$ProductPrice = $_POST['Price'];
$Gender = $_POST['Gender_ID'];
//database query to add product
$insertStringProduct = "INSERT into Product(Product_Name, Price,Gender_ID)
VALUE('$ProductName', '$ProductPrice', '$Gender')";
$result = mysql_query($insertStringProduct);
echo ("<p1>Product added Successfully</p1>");
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}
//function for the form page
function showForm()
{
//First form for adding new product
$self = htmlentities($_SERVER['PHP_SELF']);
echo("<form action = '$self' method='POST'>
<fieldset>
<legend>Adding New Product</legend>
Product Name: <input name='Product_Name' type='text' size = '40'>
<br /><br />
Price: <input name='Price' type='text' size = '20'><br><br />
Gender:
<select name='Gender_Description'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[0]</option>");
}
echo("
</select>
<br/><br/>
<input type='submit' name='sAddProduct' value = 'Add'/>
<input type='reset' value='Clear' />
</fieldset>
</form>");
}
The result ( nothing added)
However, when I change the code to
Gender:
<select name='Gender_ID'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_ID from Gender";
$result = mysql_query($dbQuary);
It's working
Can anyone help me with this?
In addNewProduct you are expecting $_POST['Gender_ID'] to be set. So of course, <select name='Gender_Description'> would not work, because Gender_Description != Gender_ID. That's also why it does work when you change it.
I'm assuming what you want to achive is to display the gender description, and it still to work. For that, you need both the id and the description:
$dbQuary = " SELECT DISTINCT Gender_ID, Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
Security
Your code is extremely unsafe. You are using mysql_* which is deprecated since 2013, and you are not sanitizing the input in any way, so your code is open to SQL injection (which is possibly in all kinds of queries; insert, update, delete, etc, and allows for data leaks, DOS, and possibly code execution and deletion/changing of data). The preferred way to prevent this are prepared statements (either using mysqli_* or PDO). They are not difficult to use, and the resulting code is also nicer.
You are not concatenating values as it should
Change
echo("<option value ='$row[0]'> $row[0]</option>");
to
echo("<option value =". '$row[0]' . "> ". $row[0]. "</option>");
OR
echo("<option value ='{$row[0]}'> {$row[0]}</option>");
EDIT:
Change your While-loop
while($row = mysql_fetch_array($result,MYSQL_BOTH)) {
echo("<option value ='{$row['gender_id']}'> {$row['gender_description']}</option>");
}
This will generate a Select list showing the Gender Description and and values will be numeric(of database)

How to submit the multiple rows form data with a single submit in PHP

Here is my code.
I made a form with multiple rows which will be updated in a single submit.
I searched in forums, but didn't find the exact answer.
<form method='POST' action='demo24.php'>
<table width="500px" height="500px">
<tr><th>SETNAME</th><th>POST</th></tr>
<?php
$query = "SELECT name,setid FROM `set` LIMIT 0 ,10";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
while($row = mysql_fetch_array($result))
{
$output .='<tr><td><input type="text" value="'.$row['name'].' '.$row['setid'].'" name="name'.$row['setid'].'">'.$row['name'].'</td><td><input type="checkbox" value="'.$row['setid'].'" name="setid"></td></tr>';
}
echo $output;
?>
</td><td><input type='submit' value='submit' name='submit'/></td></tr>
</table>
</form>
Note that you can use something like name[] in multiple input fields to send an array to the server:
<input type="text" name="row[]" />
<input type="text" name="row[]" />
On the server side $_POST['row'] will look like this:
Array (
[0] => first_input,
[1] => second_input
)
You can do this for all fields (id, row, etc.) and then loop through $_POST['id'] etc. to get all entries back together. Be sure to validate enough, i.e. make sure that those fields are indeed arrays, that all are of the same size, etc.
The MySQL family of PHP is deprecated and support thereof will disappear. Please look into PDO or MySQLi to execute SQL code instead.
If your form method as 'post' then you can use this code :
if(isset($_POST['submit']))
{
$query = "SELECT name,setid FROM `set` LIMIT 0 ,10";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
while($row = mysql_fetch_array($result))
{
$id = $row['setid'];
$name = $_POST['name'.$id];
//here will be you update code. set value will be $name and update where setid = $id
}
}

Form not displaying in PHP [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
So I have a page using PHP and a MySQL query. What I'm wanting to do is create basically an "edit" page that takes data from my database and uses it to show the values in various inputs. The user can then change the data in the input which will then update the corresponding MySQL table row. However, for whatever reason the page is NOT displaying the form, but rolling over to the else statement. I can verify the $_SESSION['weaponName'] is working, because it will echo the correct thing. Any ideas on why the form will not show up for me?
edit.php
<?php
session_start();
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$weaponName = $_SESSION['weaponName'];
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
if(mysqli_num_rows($query)>=1){
while($row = mysqli_fetch_array($query)) {
$creator= $row['creator'];
$weaponCategory= $row['weaponCategory'];
$weaponSubCategory= $row['weaponSubCategory'];
$costAmount= $row['costAmount'];
$costType= $row['costType'];
$damageS= $row['damageS'];
$damageM= $row['damageM'];
$critical= $row['critical'];
$rangeIncrement= $row['rangeIncrement'];
$weight= $row['weight'];
$weaponType= $row['weaponType'];
$masterwork= $row['masterwork'];
$attributes= $row['attributes'];
$specialAbilities= $row['specialAbilities'];
$additionalInfo= $row['additionalInfo'];
}
?>
<form action="weaponEditUpdate.php" method="post">
<input type="hidden" name="weaponName" value="<?php echo $weaponName;?>">
Weapon Name: <input type="text" name="weaponName" value="<?php echo $weaponName;?>">
<br>
Weapon Category: <select name="weaponCategory">
<?php while ($row = mysqli_fetch_array($query)) {
echo "<option value='" . $row['weaponCategory'] ."'>" . $row['weaponCategory'] ."</option>";
} ?>
</select>
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
As requested by OP (from comment conversations)
Instead of
if(mysqli_num_rows($query)>=1){
use
if(mysqli_num_rows($query) >0){
You're mixing functions
mysqli_connect("localhost","username","password","db_name");
Won't work with
mysql_query("SELECT * FROM weapons limit 1");
Try
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
And then
if($query->num_rows >= 1)
change this
$query = mysql_query("SELECT * FROM weapons limit 1");
to
$query = mysqli_query("SELECT * FROM weapons limit 1");
BUT omg all your code is mysql while you connected by mysqli !! .
You connect with mysqli, which is fine. THEN, you attempt to run queries via mysql. Those are two separate extensions. You can't mix them as they won't "communicate" with one another. Stick to mysqli.

Form processing won't pass value

i have this code which permits me to do a request in order to make a query!
Now the form which is processed has this code:
<form action="edit_images.php" method="post">
<input type="hidden" value="<? echo $gal_id1 ?>" name="img_id1" />
<input type="submit" value="Edit All Images" />
</form>
While the query is like this :
$img_id=$_REQUEST['img_id1'];
$sql="SELECT * FROM tbl_images WHERE Img_gal_id='$img_id'";
But it seems like it won't take the value...
I mean, it doesn't recognize the $img_id, which i have printed before and takes the exact value.
Let me show you the query i use in order to retrieve it:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
if(isset($myErrors) && $myErrorsP!=''){
} else {
$row = mysql_fetch_row($query);
mysql_free_result($query);
$gal_id = $row[0];
$gal_id1 = $row[0];
$gal_title = $row[1];
$gal_image = $row[2];
}
You are missing a ; on the end of your echo that isn't outputting the value as expected. Additionally, you are using short tags, which could be causing problems. You might want to swtich to using <?php as an opening over <? on it's own.
<input type="hidden" value="<?php echo $gal_id1; ?>" name="img_id1" />
Lastly, you are using zero protection against injection attacks. Please, research prepared statements in PDO and update your code. The first injection attack you don't have will thank you for it.
Edit: When you run into a problem like this, it is often good practice to echo out the $sql just before you execute it.
you could do this in the future with:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
echo $sql."<br>\n";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
which would have probably given you an excellent indication of what the problem was.

Categories