Mysql table cell doesn't change value on click - php

I am trying to write a php code that changes the availability of a certain apartment. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "bla";
$password = "blabla";
$dbname = "testDB";
// Create connection
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}else{
echo "Connected successfully to the database: " . $dbname . "<br><br>";
}
$query = "SELECT * FROM test";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo "id: " . $row["id"] . " // Address: " . $row["address"] . " // Rooms: " . $row["rooms"] . " // Availability: " . $row["availability"] . ".<br>";
?>
<form method ="post" action ="<?php $_PHP_SELF ?>">
<input name="update" type="submit" value="Change Availability">
</form>
<?php
if(isset($_POST["update"])) {
$avail = mysqli_query($connect,"SELECT availability FROM test WHERE id='1'");
$availCheck = mysqli_fetch_array($avail);
settype($availCheck, "int");
if($availCheck == 1){
$upAvail = mysqli_query($connect,"UPDATE test SET availability='0' WHERE id='1'");
}else{
$upAvail = mysqli_query($connect,"UPDATE test SET availability='1' WHERE id='1'");
}
}
?>
</body>
</html>
And this is the output I get:
Connected successfully to the database: testDB
id: 1 // Address: 3787 cote des neiges // Rooms: 2 // Availability: 1.
Change Availability
So here is my issue. When the availability is 1 and I press the button it changes to 0. But after that, when I press the button again, it doesn't change back to 1.
Why is that?
Thank you for the help.

You're not toggling the availability. The mysqli_fetch_array fetches the row from the test table matching the id (id=1). As a result, $availCheck will always equal 1 after you cast the non-empty array to an integer.
You can replace all that logic with a single MySQL query to toggle the value.
UPDATE test SET availability = IF(availability = 1, 0, 1) WHERE id=1
I think what you wanted to do:
$availCheck = mysqli_fetch_array($avail)['availability'];

Related

Wordpress database connection plugin

I made a kind of plugin just for the database connection it works but if i activate my plugin the page wil go a little bit down so actually my site will become ugly
$servername = "xxxx"; // naam of ip van de machine ... 127.0.0.1
$username = "xxxx"; //naam van gebruiker
$password = "xxxx"; // wachtwoord
$dbname = "xxxx"; //db naam
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_GET["code"]) )
{
$code = $_GET['code'];
}
else
{
$code = '';
}
//$naam = '%DR%';
//$sql = "SELECT * FROM docenten WHERE naam=\"$naam\"";
$sql = "SELECT * FROM `cadeaubon` WHERE Kortingscode like \"$code\"";
//echo $sql; //debuggen
echo "<BR>";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
echo "<table>";
while($row = mysqli_fetch_assoc($result)) {
echo "- ID: " . $row["ID"]. " - Kortingscode: " . $row["Kortingscode"]. " - Aantal personen: " . $row["AantPersonen"] . " - Naam: " . $row["Naam"] . " - Achternaam: " . $row["Achternaam"] . " - Leeftijd: " . $row["Leeftijd"] . " - Datum: " . $row["Datum"]."<br>";
}
echo "</table>";
} else {
echo "";
}
mysqli_close($conn);
this is my code and i thought maybe it will help if the result will display at the bottom of the page but i dont know how
I guess you left there <br> from your debug echo:
//echo $sql; //debuggen
echo "<BR>";
However I don't know where in code this gets executed and how it integrates with WordPress. If the following table is shown inside content area of the page, the <br> shouldn't affect your site design other than pushing the table one line down.
It also seems to be a bit of overkill to create your own database connection - I would think WordPress already is connected and it would be preferable to use its own connection, unless it is a completely different database.

update mysql record to add count when button on loop is clicked

I have a form that displays candidates with their details using a mysql while loop and below each candidate is a "vote" button which is also inside the loop. I need to add 1count to a record when their button is clicked. My problem is the buttons inside the loop has the same names so they are all affected with the update even if only one is clicked.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ename FROM election_title ORDER BY `sdate` ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$ename= $row['ename'];
?>
<p><font size= "6px" align = "center" color = "#efbf77"> <?php echo $row['ename']. "<br>";?></p>
<?php
$sql = "SELECT * FROM candidate_list T1 INNER JOIN election_title T2 ON T1.ename = T2.ename WHERE T1.ename LIKE '%$row[ename]%';";
$res = $conn->query($sql);
if ($res->num_rows > 0) {
while($rowval = $res->fetch_assoc()) {
$id= $rowval['id'];
$image_content= $rowval['image_content'];
$ename= $rowval['ename'];
$pos= $rowval['pos'];
$fname= $rowval['fname'];
$mname= $rowval['mname'];
$lname= $rowval['lname'];
?>
<div class = "cand">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode( $rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>
<form action="castvote.php" method="post">
<INPUT TYPE=submit NAME="<?php echo $fname; ?>" VALUE="<?php echo 'Vote ' .$fname; ?>">
</div>
<?php
}
} else {
echo "No candidate(s) listed.";
}
?>
<?php
}
} else {
echo "0 results";
}
?>
And this is my query.
<html>
<head>
<title>NSDCI Voting System</title>
<link rel="stylesheet" href="css/style.css">
</head>
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'voting_system';
$fname = $_POST['fname'];
$con = mysqli_connect($host, $user, $pass, $db);
if($con)
{
$sql = "UPDATE candidate_list SET votes = votes +1 WHERE fname = $fname";
$query = mysqli_query($con, $sql);
if($query)
echo 'data inserted succesfully';
}
echo 'connected succesfully to the db!';
?>
How can i query a WHERE clause that matches my button name. Thanks in advance
One way would be to assign, to each button, a dataset attribute - such as data-id=$rowval['id'] and use javascript to read that dataset value and either send an ajax request or submit the form with that value. You would not need a form for every candidate - one form should suffice and change the value of a hidden field.
Presumably fname means forename or firstname - if so then that is not a good item to use in your update statement, especially if the candidate's firstname is John for example where there a likely to be many. As each candidate in the db has his/her own ID it would make sense to use the ID for the update because that is guaranteed(?) to be unique.
<html>
<head>
<title>vote</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var form=document.forms['vote'];
var bttns=document.querySelectorAll('input.candidate');
for( var n in bttns )if( bttns[ n ].nodeType==1 )bttns[ n ].addEventListener('click',function(e){
form['id'].value=this.dataset.id;
form.submit();
}.bind(bttns[n]),false);
},false);
</script>
</head>
<body>
<form id='vote' action="castvote.php" method="post">
<input type='hidden' name='id' />
</form>
<?php
if ( $conn->connect_error )exit('unable to connect to database');
/*
not sure about the query but there should be no need to use nested queries in a loop
when a join or a selection as below should suffice.
*/
$sql="select * from `candidate_list` c
inner join `election_title` e on c.`ename` = e.`ename`
where c.`ename` in ( select distinct `ename` from `election_title` );";
$res = $conn->query( $sql );
if( $res->num_rows > 0 ) {
while( $rs = $res->fetch_object() ){
$id=$rs->id;
$pos=$rs->pos;
$image=$rs->image_content;
$ename=$rs->ename;
$fname=$rs->fname;
$mname=$rs->mname;
$lname=$rs->lname;
$pname=$rs->pname;
echo "
<div class='cand'>
<img src='data:image/jpeg;base64," . base64_encode( $image ) . "' />
<p class='bold'>
{$fname}{$mname}{$lname}
</p>{$pos}
<br/>
{$pname}
<input type='button' data-id='{$id}' class='candidate' value='Vote for {$fname}' />
</div>";
}
}
?>
</body>
</html>
Using the above methodology would mean that the PHP code that updates the db needs to be changed to use the ID ( ie: $_POST['id'] )
$sql = "UPDATE candidate_list SET votes = votes+1 WHERE id='{$_POST['id']';";
I realise the code is vulnerable to sql injection - prepared statements is the way forward.
One thing I noticed after posting my answer was the base64_encode( $image ) line - if this is coming from the db, as it is, then I guess that would be the path to the image rather than RAW data? If that is the case the line ought to read base64_encode( file_get_contents( $image ) )
In response to the valid comment about insecure code - how the use of prepared statements could be used to mitigate against sql inection.
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<title>NSDCI Voting System</title>
<link rel='stylesheet' href='css/style.css'>
</head>
<body>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['id'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'voting_system';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
$sql='update `candidate_list` set `votes` = `votes`+1 where `id`=?';
$stmt=$db->prepare( $sql );
if( $stmt && $id ){
$stmt->bind_param( 's', $id );
$result=$stmt->execute();
echo $result ? 'data inserted succesfully' : 'oops';
}
}
?>
</body>
</html>
I am changing the below part of your code.
<div class = "cand">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode($rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>
<form action="castvote.php" method="post">
<INPUT TYPE=submit NAME="<?php echo $fname; ?>" VALUE="<?php echo 'Vote ' .$fname; ?>">
</div>
Try considering the idea of not using form. You can use a hyperlink with the action script. Pass the AutoIncrement value from the target table of the selected candidate via the URL. After this, fetch the value in your action script using $_GET and do the update. To ensure that the action script is not accessed directly, add the isset($_GET) validation. Below is the code.
<div class = "cand">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode($rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>
//I am changing your code here.
Vote <php echo $fname; ?>
</div>
Now in your action script, use the below code.
if (isset($_GET['id'])) {
$id_to_update = $_GET['id'];
//Have your PHP update code here with the target id.
}
Hope this helps.

Displaying results of SQL query as a table?

I am trying to output the results of an SQL query as a table on a page on my website. I have found a few solutions online but I can't get any of them to work properly. Right now I copied and pasted a bit of code to just output the first two columns but I can't figure out how to get every column in a table. I am new to PHP and web development in general so any help would be appreciated.
My PHP:
<?php
SESSION_START() ;
$servername = "localhost";
$username = "MY USERNAME";
$password = "MY PASSSWORD";
$dbname = "MY DATABASE NAME";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//$_session['userid'] = $userlogged;
$sql = "SELECT * FROM `climbs` WHERE `userlogged` = '" . $_SESSION['userid'] . "'";
$result = mysqli_query($conn,$sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["climb-id"]. "</td><td>" . $row["climbname"]. " " . $row["cragname"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
check with var_dump :
some like that:
$result = mysqli_query($conn,$sql);
var_dump($result);
if ($result->num_rows > 0) {
maybe the query it's wrong.

PHP mySql Query Problems with call

I am trying to make a query call from PHP. However, I am not sure why it is not working properly. It looks like there is something wrong with what I am trying to do with the query. Everything was working correctly before I added the where clause and the bindParam. The code is executing correctly and then stops after I make the query and the binding. Can someone see if I did that correctly?
Might have something to do with post call to gender. I could not echo out the $gender.
Thanks for any insights!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Practice Work 5</title>
</head>
<body>
<form action="babynames.php" method = "post">
Year:<br>
<input type="text" name="year">
<input type="submit" value="Submit">
</form>
<select name = "gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</body>
</html>
<?php>
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "baby";
$year = $_POST['year'];
$gender = $_POST['gender'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames where Year = ? and Gender = ?";
$sql -> bindParam (1, $year, PDO::PARAM_INT);
$sql -> bindParam (2, $gender, PDO::PARAM_STR);
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Year: ". $row["Year"]. " ; Name: ". $row["Name"]. " ; Ranking: " . $row["Ranking"] . " ; Gender: " . $row["Gender"]. " ". "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Your variable $sql is string, not an object.
According http://php.net/manual/en/mysqli-stmt.bind-param.php
You have to prepare the statement before bind params like:
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("is", $year, $gender);
$stmt->execute();
$result = $stmt->get_result();
$processedRows = 0;
while ($row = $result->fetch_assoc()) {
$processedRows++;
echo "<br> Year: ". $row["Year"]. " ; Name: ". $row["Name"]. " ; Ranking: " . $row["Ranking"] . " ; Gender: " . $row["Gender"]. " ". "<br>";
}
if (empty($processedRows)) { echo "0 results"; }
}
$conn->close();
Change this
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames where Year == ? and Gender == ?";
to
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames WHERE Year = ? AND Gender = ?";

MySQL php select statement using WAMP server

Im trying to display a database table in my html page but cant seem to get it to work. (code below):
<!DOCTYPE html>
<html>
<body>
<h1> Table </h1>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Library";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `books` ORDER BY `Category` ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["ISBN"]. " Name: ". $row["firstname"]. " - Author: " . $row["BookAuthor"]. " Category: " . $row["Category"]. " - Quantity: " . $row["Quantity"]. " - Price: " . $row["Price"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
Im using WAMP server and the "books" table is located in a database called Library. However the table doesnt display and all i get is the php code being shown.
Any idea on whats gone wrong?
Thanks!
Is your WAMP running? (Check the system tray icon. It should be green)
Did you mess with PHP or Apache configs?
Is the file extension .php? It has to be.
Is other PHP displaying properly?

Categories