Table with database values and user input - php

So I've been wrestling with this issue on and off for quite a while now, and just like driving around lost in a strange city, I am finally breaking down for direction! I am developing table with values from a database, but also need a column that will process user input. I have been able to display the table but my input is not updating the necessary database element. Code below:
<?php
include("pogsatbetbuddy.inc.php");
$cxn=mysqli_connect($host,$username,$password,$db_name)
or die("Did Not Connect");
$query="SELECT * FROM $tbl2_name ORDER BY $tbl2_name.$col_name ASC";
$result=mysqli_query($cxn,$query)
or die("Query Not Working");
echo"<table border='1'
<form name='payments' action='' method='POST'>
<tr>
<td class='update' colspan='5'>
<button data-theme='b' id='submit' type='submit'>Update</button>
</td>
</tr>
<tr>
<th class='profile'>Last Name</th>
<th class='profile'>First Name</th>
<th class='profile'>Saturday Payment Owing</th>
<th class='profile'>Enter Payment</th>
<th class='profile'>Saturday Balance</th>
</tr>";
while ($row=mysqli_fetch_assoc($result))
{
extract ($row);
echo"<tr>
<td class='profile'>$lastname</td>
<td class='profile'>$firstname</td>
<td class='profile'>$owingsat</td>
<td class='profile'><input type='number' name='paidsat' value=''/></td>
<td class='profile'>$owingsat-$paidsat</td>
</tr>";
}
echo "</form>";
echo "</table>";
This displays the table in the way I want. Having worked through the results of the following code, it seems that I am returning a null value, so I am thinking I have an issue with either the form action or the submit Update button, but can not find the solution after much experimentation and searching. Balance of code below:
if(isset($_POST['paidsat']))
{
$paidsat = $_POST['paidsat'];
if(($paidsat) != null)
{
$stmt = $cxn->prepare("UPDATE $tbl2_name SET paidsat = ? WHERE firstname=? and lastname=?");
$stmt->bind_param('sss', $paidsat, $firstname, $lastname);
$status = $stmt->execute();
if($status === true) //To check if the execute was successful
{
echo("<p class='click'>You have successfully added the payment for $firstname $lastname\n<br /></p>");
}
}
else echo"Not Successful";
}
else echo "<p class='click'>Make your changes as required</p>";
mysqli_close($cxn);
Everything comes to a crashing halt at the second if statement.....or should I say, although things look pretty, they don't function! Thanks in advance, appreciate any help!

Be sure you have a proper value for $tbl2_name checking
var_dump($tbl2_name)
in your code before the update
and for debug try using a string concatenation like
"UPDATE " . $tbl2_name . " SET paidsat = ? WHERE firstname=? and lastname=?";
and try use
if( $paidsat != NULL )
and last check if you have proper value for update
paidsat = ? WHERE firstname=? and lastname=?
Try
var_dump( $paidsat);
var_dump( $firstname);
var_dump( $lastname);
and build a proper select for test if you value math the rows you think and
test this select in you db console

Related

How to delete the entire row in the database from html table instead of deleting entire table in the database

I have added delete button to the html table on each row and when clicked on delete button the entire row should be deleted but instead whole table in the database is being deleted.
here is my code for admin.php
<div class="container mt-3 ml-3">
<table class="table">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Email</th>
<th>Rating</th>
<th>Review</th>
<th>Image</th>
<th>Suggestion</th>
<th>NPS</th>
<th>Delete</th>
</tr>
</thead>
<tbody class="table-warning">
<?php
include 'database_conn.php'; // makes db connection
$sql = "SELECT feedbackID, name, email, rating, review, image, suggestion, nps
FROM feedback
ORDER BY feedbackID Desc";
$queryResult = $dbConn->query($sql);
// Check for and handle query failure
if($queryResult === false) {
echo "<p>Query failed: ".$dbConn->error."</p>\n";
exit;
}
// Otherwise fetch all the rows returned by the query one by one
else {
if ($queryResult->num_rows > 0) {
while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>
<td>{$rowObj->feedbackID}</td>
<td>{$rowObj->name}</td>
<td>{$rowObj->email}</td>
<td>{$rowObj->rating}</td>
<td>{$rowObj->review}</td>
<td>{$rowObj->image}</td>
<td>{$rowObj->suggestion}</td>
<td>{$rowObj->nps}</td>
<td><a id='delete' href=delete.php?id={$rowObj->feedbackID}>Delete</a></td>
";
}
}
}
?>
</tr>
</tbody>
</table>
</div>
And here my code for delete.php. I think there is something wrong in the sql query I made.
<?php
include 'database_conn.php'; // makes db connection
$sql = "DELETE FROM feedback WHERE feedbackID=feedbackID";
if ($dbConn->query($sql) === TRUE) {
echo "Record deleted successfully. Please go to Customer Feedback Page by clicking"; echo "<a href='http://unn-w18031735.newnumyspace.co.uk/feedback/admin.php'> here</a>";
} else {
echo "Error deleting record: " . $dbConn->error;
}
$dbConn->close();
?>
This is wrong:
DELETE FROM feedback WHERE feedbackID=feedbackID
it is always true as it will be equal to itself.
What you want to use is parameters here. $_GET['id'] is where the id is.
If you use PDO, something like
$stmt = $dbConn->prepare("DELETE FROM feedback WHERE feedbackID=:feedback_id");
$stmt->execute(['feedback_id' => $_GET['id']]);
For mysqli,
$stmt = $mysqli->prepare("DELETE FROM feedback WHERE feedbackID=?");
$stmt->bind_param("i",$_GET['id']);
$stmt->execute();
this solution in delete.php has worked.
$feedbackID = $_GET["id"];
$sql = ("DELETE FROM feedback WHERE feedbackID= '$feedbackID'");

Like to jQuery sum values

I like to sum all values with script but get it the result: total:NaN
(need to sum all columns except the first column)
The code PHP and script are in the same file and this is my code:
For php:
<table id="table">
<thead class="thead-dark">
<tr class="titlerow">
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>col5</th>
</tr>
</thead>
<tbody>
<tr>
<?php
include("conn.php");
$result = mysql_query("SELECT id,name,col1,col2 FROM table GROUP BY name");
while($test = mysql_fetch_array($result))
{
$id = $test['id'];
echo"<td class='rowDataSd'>".$test['col1']."</td>";
echo"<td class='rowDataSd'>".$test['col1']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo "</tr>";
}
mysql_close($conn);
echo '<tfoot>
<tr class="totalColumn">
<td>.</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</tfoot>';
?>
</table>
For script:
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
Where is the exact problem?
I'm not sure, but... as far as i know, and maybe i'm wrong (would be happy to get advise on that) => mysql_fetch_array and mysql_query is kinda "dead" and instead, today you should use: mysqli_fetch_array and mysqli_result (see the additional i), and that depends on the version you are running on your server that is. Does the query works for you?. If not, i would defently look into that.
See an example here:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
I wouldn't sum them with jQuery at all. I would do it in PHP:
...
<tr> <!--- this tr is out of place, needs to be in the loop -->
<?php
//include("conn.php"); this should be require as it's necessary
//include will ignore missing files, require with throw an error
//this code will not work without that file, so let PHP tell you
//when it goes missing, instead of wondering why your DB calls don't work
require "conn.php"; // inlude/require are not functions they will work with (...) but it's not best practice.
$result = mysql_query("SELECT id,name,col1,col2 FROM table GROUP BY name");
//define default values for increment without errors
$totals = ['col1'=>0,'col2'=>0,'col3'=>0,'col4'=>0,'col5'=>0];
while($test = mysql_fetch_array($result))
{
$id = $test['id'];
echo "<tr>"; //-- this is the tr from above --
//use a loop if the HTML is all the same
for($i=1;$i<=5;++$i){
$key = 'col'.$i;
echo"<td class='rowDataSd'>".$test[$key]."</td>";
//simply add the values on each iteration (sum)
$totals[$key] += $test[$key];
}
echo "</tr>"; //-- without fixing the open tag as mentioned above, your HTML would be messed up --
}
mysql_close($conn);
echo '<tfoot>';
echo '<tr class="totalColumn">';
echo '<td>.</td>';
for($i=1;$i<=5;++$i){
echo '<td class="totalCol">total:'.$totals['col'.$i].'</td>';
}
echo '</tr>';
echo '</tfoot>';
...
If this stuff doesn't change dynamically (which it doesn't seem to), there is no need to do it with Javascript.
You can also reduce the code by using a simple for loop.
Cheers!

Deleting users With PDO

Hello every one i have probleme with my form of deliting users , when i submit the button nothing happend what is the problem , everything work on the db when i fetch infos they come but when i click on delete nothing happend
<?php
$host ="localhost";
$dbname ="justnew";
$u_name="root";
$u_pass="youcef02";
echo'
<table border="1px solid #efefef" width="42%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Password</th>
<th>DELETE</th>
</tr>
';
try{
$Conn = new PDO("mysql:host=$host;dbname=$dbname",$u_name,$u_pass);
}
catch(PDOEXCEPTION $e){
echo'There is a prblm' .$e->getMessage();
}
$sql = "SELECT * FROM addu";
$result = $Conn->query($sql);
while($row = $result->fetch(PDO::FETCH_OBJ)) {
echo"
<tr>
<td>" .$row->u_id."</td>
<td>" .$row->u_name."</td>
<td>" .$row->u_pass."</td>
<td><button name='dlt'><a href='attribute.php?
type=dlt&u_id=".$row->u_id."' name='dlt'>DELETE</a></button></td>
</tr>
";
}
if($_GET['type'] == ['dlt']){
$id = intval ($_GET['u_id']);
$Dsql = "DELETE * FROM `addu` WHERE `u_id` ='".$id."'";
$Dresult = $Conn->exec($Dsql);
}
?>
Seeing nobody wanted to post an answer for this, I am submitting the following.
As stated: if($_GET['type'] == ['dlt']) is invalid. The brackets around the dlt need to be removed and would have thrown an syntax error.
if($_GET['type'] == 'dlt')
You should however, check if the GET array is set/not empty though, since without it, that too will throw an undefined index warning having error reporting set on your system.
if(isset($_GET['type']) && $_GET['type'] == 'dlt')
or
if(!empty($_GET['type']) && $_GET['type'] == 'dlt')
Then the DELETE'ing part of your query is also invalid.
It should read as:
$Dsql = "DELETE FROM `addu` WHERE `u_id` ='".$id."'";
https://dev.mysql.com/doc/refman/5.7/en/delete.html
The asterisk is only valid with a SELECT statement:
https://dev.mysql.com/doc/refman/5.7/en/select.html
Having used (PDO) error handling, you'd of surely gotten back an syntax error:
https://php.net/manual/en/pdo.error-handling.php
Now this bit could have adverse effect:
<td><button name='dlt'><a href='attribute.php?
type=dlt&u_id=".$row->u_id."' name='dlt'>DELETE</a></button></td>
</tr>
";
It's (usually) best to have this all in one line:
<td><button name='dlt'><a href='attribute.php?type=dlt&u_id=".$row->u_id."'>DELETE</a></button></td>
</tr>
";
The added spaces could count here.
Note: You used the name attribute twice.
If the above fails, then the <a href></a> shouldn't be inside a <button></button>, just use the <a href></a>.

Why data from my database is not displaying?

Hey guys I'm pretty new at PHP, I'm not too sure what Ive done wrong and I've been working at this for a few hours and cant seem to see whats wrong with it (there's no error which makes things more fun) what it actually does, it runs fine but it does not display the data from my database and only shows up with the column headers and that's it.
I would appreciate any advice at this point. What my code does is that it grabs some information 'staffID' from a form and uses that to display data that associates with it (like a search function) I'm using a 'join' function just for practice with the database I'm using.
As I said I'm completely new to this so this so I could be completely wrong with my code
<?php $staffidstr = $_GET["staffID"];
$conn = mysql_connect("xxxxxxx", "xxxxxx", "xxxxxxx");
mysql_select_db("xxxxxxxx", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT orderID, orderDate, shippingDate, staffName
FROM purchase, staff
WHERE purchase.staffID = staff.staffID
AND staff.staffID = '%$staffidstr%'
ORDER BY staff.staffName";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
?>
<?php echo "$staffidstr"; ?>
<table border="1" summary="Purchase Details">
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Shipping Date </th>
<th>Staff Name</th>
</tr>
<?php
while ($row = mysql_fetch_array($rs)) { ?>
<tr>
<td><?php echo $row["orderID"]?></td>
<td><?php echo $row["orderDate"]?></td>
<td><?php echo $row["shippingDate"]?></td>
<td><?php echo $row["staffName"]?></td>
</tr>
<?php }
mysql_close($conn); ?>
I'm pretty sure it's following part of the WHERE clause
staff.staffID = '%$staffidstr%'
That should be most likely
staff.staffID = '$staffidstr'
The % character has no special meaning using the = operator, so your query will return not a single row.

Inserting specific values into a DB, and displaying it on a table?

I'm trying to insert specific values(knife, and blanket) into a Database, but's not inserting into the DB/table at all. Also, I want to display the inserted values in a table below, and that is not working as well. It is dependant on the insert for it to show on the table. I am sure, because I inserted a value through phpmyAdmin, and it displayed on the table. Please, I need to fix the insert aspect.
The Insert Code/Error Handler
<?php
if (isset($_POST['Collect'])) {
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}else {
// this makes sure that all the uses that sign up have their own names
$sql = "SELECT id FROM objects WHERE object='".mysql_real_escape_string($_POST['Object'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This object has already been taken.!';
} else{
$sql="INSERT INTO objects (object)
VALUES
('$_POST[Object]')";
echo "".$_POST['object']." ADDED";
}
}
}
?>
TABLE PLUS EXTRA PHP CODE
<p>
<form method="post">
</form>
Pick Object: <input name="Object" type="text" />
<input class="auto-style1" name="Collect" type="submit" value="Collect" />
</p>
<table width="50%" border="2" cellspacing="1" cellpadding="0">
<tr align="center">
<td colspan="3">Player's Object</td>
</tr>
<tr align="center">
<td>ID</td>
<td>Object</td>
</tr>
<?
$result = mysql_query("SELECT * FROM objects") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table?>
<tr>
<td><label for="<?php echo $row['id']; ?>"><?php
$name2=$row['id'];
echo "$name2"; ?>
</label></td>
<td><? echo $row['object'] ?></td>
</tr>
<?php }// while loop ?>
</table>
</body>
if(($_POST['Object'])!= knife || ($_POST['Object'])!= blanket)
THese value knife and blanket are string. So you may need to use quotes around them to define them as string, or php won't understand ;)
If the primary key of Objects is id and it is set to auto-increment
$sql = "INSERT INTO objects SET id = '', object = '".$_POST['Object']."'";
try
$sql= "INSERT INTO objects(object) VALUES ('".$_POST['Object'].")';
and you should probably put an escape in there too
You insert query is nor correct.
$sql = "INSERT INTO objects (id, object) values('','".$_POST['Object']."') ";
and this code
if(($_POST['Object'])!= "knife" || ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
will always be executed value of object is knife or blanket, because a variable can have one value. You must use
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
Your SQL syntax is wrong. You should change the:
INSERT INTO objects SET id = '', object = '".$_POST['Object']."'
to
INSERT INTO objects ( id, object ) VALUES ('', '".$_POST['Object']."'
If you want your inserts to also replace any value that might be there use REPLACE as opposed to INSERT.

Categories