php - issue when update the db - php

I'm working on updating text to sql.
I am facing problem in my code below not updating the db, but when i change the where pid='$data[pid]' statement to some index like where pid='3', it works.
I'm new in programming. can you explain why?
thanks.
<?php
//include "koneksi.php";
$host="localhost";//nama server
$user="root";//username
$pass="";//password
$dbnama="skripsi";//nama database yang dipilih
mysql_connect($host, $user, $pass) or die ("Database tidak dapat di akses");//koneksi ke database
mysql_select_db($dbnama); //database yang dipilih
?>
<?php
$query="select pid, username, user, datapos, datanet, dataneg, status from trainklasifier";
$hasil=mysql_query($query);
?>
<html>
<head>
</head>
<body>
<table border="1" align="center">
<tr>
<td >ID</td>
<td >Model Klasifikasi</td>
<td >Creator</td>
<td width="300px">Data Positif</td>
<td width="300px">Data Netral</td>
<td width="300px">Data Negatif</td>
<td width="100px">Status</td>
<td width="100px">Aksi</td>
</tr>
<?php
$datapos=$data[datapos];
$datanet=$data[datanet];
$dataneg=$data[dataneg];
$dataid=$data[pid];
while ($data=mysql_fetch_array($hasil)){
echo ("<tr><form id='form1' action='' method='post'>
<td><textarea rows='1' cols='1' name='taid' value='$dataid' disabled>$data[pid]</textarea></td>
<td>$data[username]</td>
<td>$data[user]</td>
<td><textarea rows='4' cols='35' name='tapos' >$data[datapos]</textarea></td>
<td><textarea rows='4' cols='35' name='tanet' value='$datanet'>$data[datanet]</textarea></td>
<td><textarea rows='4' cols='35' name='taneg' value='$dataneg'>$data[dataneg]</textarea></td>
<td>$data[status]</td>
<td><input type='submit' name='btsubmit' value='Train' /></td>
</form></tr>");}
?>
<?php
$inputpos=$_POST['tapos'];
$inputnet=$_POST['tanet'];
$inputneg=$_POST['taneg'];
$id=$_POST['taid'];
if (isset($_POST['btsubmit'])){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("skripsi") or die(mysql_error());
mysql_query("update trainklasifier set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg' where pid='$data[pid]'");
}
echo $inputpos;
?>
</table>
</body>
</html>

If you use arrays inside string interpolation you need to wrap then in {}
For example
"where pid = '{$data['pid']}'"
Also, it appears you are not quoting your array keys. $data[key] should be either $data["key"] or $data['key'] unless you are using a variable, as in $data[$key]

I feel that $data['pid'] may be wrong. Consider:
$datapos=$data[datapos];
$datanet=$data[datanet];
$dataneg=$data[dataneg];
$dataid=$data[pid];
...here $data is okay, I assume...
while ($data=mysql_fetch_array($hasil)){
...here you cycle $data, and so exit when $data is NULL...
<td><input type='submit' name='btsubmit' value='Train' /></td>
</form></tr>");}
^---
Here you have closed the cycle (I'd use a HERE-document if I were you, BTW), and so
from now on $data is NULL.
$id=$_POST['taid'];
Here you have retrieved $id.
if (isset($_POST['btsubmit'])){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("skripsi") or die(mysql_error());
mysql_query("update trainklasifier set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg' where pid='$data[pid]'");
And here you use $data[pid] which does not exist. The syntax would actually work, it is not too clear ({$data['pid']} would be better), but the problem is that $data is no longer an array here.
You probably want to use $id instead:
$query = <<<QUERY1
update trainklasifier
set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg'
where pid='$id';
QUERY1;
mysql_query($query);
Checking _POST
The POST checking code, if it is in the same file, ought to be enclosed in a suitable check that a POST was indeed originated:
<?php
$need = array('tapos','tanet','taneg','taid','btsubmit');
$haveAll = true;
foreach($need as $fld)
if (!isset($_POST[$fld]))
$haveAll = false;
if ($haveAll) {
// Now we can proceed with POST.
$inputpos=$_POST['tapos'];
$inputnet=$_POST['tanet'];
$inputneg=$_POST['taneg'];
$id=$_POST['taid'];
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("skripsi") or die(mysql_error());
// This is a here-document. Things to check: no two identifiers in the
// same PHP file (use QUERY1, QUERY2, ...). No spaces around the first
// opening tag ("<<<QUERY"). The closing tag and the semicolon must be
// the only thing on the closing line, no spaces, nothing: "QUERY1;"
// (These conditions are more restrictive than necessary: to be safe).
$query = <<<QUERY1
update trainklasifier
set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg'
where pid='$id';
QUERY1;
mysql_query($query) or die(mysql_error());
}

Try this change update query like this
mysql_query("update trainklasifier set datapos='".$inputpos."',datanet='".$inputnet."',dataneg='".$inputneg."' where pid='".$data[pid]."' ");

Related

Table with database values and user input

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

Can't delete a row from a Database using a img PHP

i was doing a backoffice for my website, and to show the data i brought a table from database to show all the upgrades requested from users, and i was thinking about putting 2 images , one for update and another for deleting that same row..
# Table from Database #
?>
<div id="DBForm">
<p id="title" align="center"> Upgrades</p>
<br/>
<?php
$resultado=mysql_query("SELECT * FROM upgrades");
if (mysql_affected_rows()>=1)
{
echo "<table class='DBTable'>";
echo "<tr>
<th>Nome</th>
<th>Upgrade</th>
<th>Morada</th>
<th>Contacto</th>
<th>NIF</th>
<th>Factura</th>
<th>Data</th>
<th>N Serie</th>
<th>Cupao</th>
<th>Alterar</th>
<th>Eliminar</th>
</tr>";
while ($linha=mysql_fetch_array($resultado))
{
echo "<tr align='center'>
<td>".$linha["nome"]."</td>
<td>".$linha["upgrade"]."</td>
<td>".$linha["morada"]."</td>
<td>".$linha["contacto"]."</td>
<td>".$linha["nif"]."</td>
<td>".$linha["factura"]."</td>
<td>".$linha["data_factura"]."</td>
<td>".$linha["n_serie"]."</td>
<td>".$linha["cupao"]."</td>
<td><img src=images/alterar.png></img> </td>
<td><img src=images/eliminar.png></img> </td>
</tr>";
}
echo "</table>";
}
?>
</div>
It was all right, but when i press the img to delete, the browser says that i sucessfully deleted the row but when i go back to the page the row is still there, what it could be ?
#Code from img to delete the row#
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loja";
$tbl_name = "upgrades";
// Create connection
mysql_connect($servername, $username, $password)or die ("Não houve conexão");
mysql_select_db("$dbname");
$id=$_REQUEST['id'];
$sql="DELETE FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
if ($result)
{
echo "Registo apagado com sucesso!";
echo "<br>";
echo "<a href='upgrades.php'> Voltar a upgrades </a>";
}
else
{
echo "ERRO!";
mysql_close();
}
?>
Nothing is supplying this value:
$id=$_REQUEST['id'];
The page is being requested with just a link:
"<img src=images/eliminar.png>"
In order to supply the identifier you'll need to add it to the link. Maybe something like this:
"<img src=\"images/eliminar.png\">"
(or whatever the identifier is on $linha)
Additionally, please be aware that your code is wide open to SQL injection attacks. You'll want to look into using prepared statements instead of putting user input directly into SQL code.
Sidenote: You can safely remove the </img> tag; it's not a valid tag.

Entering secondary data into pre-existing database

I need some help. I have written a script to put first and last name into a database. This works correctly. Then I have written a script to display these names along with 4 text fields per name where student points can by typed in and then stored in the DB. The names from the DB are displayed correctly and the text fields display correctly however, when I try to put the numbers in the fields it does not put the numbers in the DB and generates "undefined index" errors. I have worked on this for a while but am just not getting it. Thanks for your help. My code is below. Thank you.
<html>
<body>
<form action="pts_summary.php" method="post">
<table border="1">
<tr>
<th>Student Name</th>
<th>First Hour</th>
<th>Second Hour</th>
<th>Third Hour</th>
<th>Fourth Hour</th>
</tr>
<br>
<?php
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$con=mysqli_connect("localhost","root","","srrdb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * From students");
while($row = mysqli_fetch_array($result))
{
echo "<tr>"."<td>".$row['fname']."&nbsp".$row['lname']."</td>".
"<td>".'<input type="text" name="hour1">'."</td>".
"<td>".'<input type="text" name="hour2">'."</td>".
"<td>".'<input type="text" name="hour3">'."</td>".
"<td>".'<input type="text" name="hour4">'."</td>"."</tr>";
}
if (isset ($_POST['submit']))
{
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
}
mysqli_close($con);
?>
</table>
<br><input type="submit" value="SUBMIT" name="submit">
</form>
</body>
</html>
You're trying to grab post data before you even check if the submit button was pressed. If the submit button wasn't pressed, you won't have values in any of the $_POST['hour#'] fields, and that will throw an undefined index error. Throw those lines AFTER the submit check like so.
if (isset ($_POST['submit']))
{
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
}
Your undefined index notices are caused by using $_POST[...] without checking if they are set. Your data is not inserting into your database, as you are only setting the INSERT query -
$sql="INSERT INTO students...
but you never execute a query.
mysqli_query($con,$sql);
try -
if (isset ($_POST['submit'])){
// put these inside isset() to prevent undefined index notices
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
//missing the query line
// Insert or die with error message
$update = mysqli_query($con,$sql) or die(mysqli_error($con));
}
Also, you are using unsanitized $_POST data so you are open to SQL Injection. Either sanitize using mysqli_real_escape_string() or better yet use prepared statements - http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

PHP + MySQL + Cookies, why is this not loading properly?

I've got a PHP page with 2 MySQL statements in various parts of the code. I'm using the generated result sets to set cookie values then call it later. Yet, when I call the cookie data, it does not update the display of the cookie values until after a 2nd refresh. To Better understand, Here's the 3 sections of code:
<?php
include 'functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$SqlStatement = "SELECT Deceased.PK_Deceased, Deceased.Date_Death, Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info WHERE Deceased.FK_Personal_Info = '".$_POST['cboDeceased']."'";
$result = ExecuteSql($SqlStatement);
if(mysqli_num_rows($result) == 1)
{
$row = mysqli_fetch_array($result);
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
setcookie('deceasedName', ($row['First_Name']." ".$row['Last_Name']), time()+360000, '/');
setcookie('deceasedDoD', $row['Date_Death'], time()+360000, '/');
}
}
?>
This is the code that pulls the data from the postback. I think that this is the part that is incorrect, but I'm not sure.
<tr>
<td width="25%" rowspan="2" align="center">Current User: <?php echo $_COOKIE['username']; ?> </td>
<td width="25%" rowspan="2" align="center">Current Deceased: <?php if(isset($_COOKIE['deceasedName']))echo $_COOKIE['deceasedName']; ?></td>
<td width="50%" rowspan="2" align="center">Deceased Date of Death: <?php if(isset($_COOKIE['deceasedDoD']))echo $_COOKIE['deceasedDoD']; ?></td>
This is the code to load the cookie data into fields and the part that takes the 2nd refresh to display properly.
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table align="center" width="500" border="0.5">
<tr>
<td width="176" align="right" style="font-weight:bold;">Please select deceased:</td>
<td width="214">
<select name="cboDeceased" id="cboDeceased">
<option>Select...</option>
<?php
$SqlStatement = "SELECT Deceased.PK_Deceased , Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info";
$res = ExecuteSQL($SqlStatement);
while($row = mysqli_fetch_array($res))
{
echo "<option value='".$row['PK_Deceased']."'>".$row['First_Name']." ".$row['Last_Name']."</option>";
}
?>
This is the code that passes a variable based on ID to the 1st code block. This part works fine.
function ExecuteSQL($SQL)
{
$con = mysqli_connect("localhost", "root", "", "exec_support_db");
$res = mysqli_query($con, $SQL);
mysqli_close($con);
return $res;
}
Here's the code for the ExecuteSQL function. I know that this isn't the problem.
I think the problem is up above in the 1st code block, but I'm not sure. I've tried everything I can and am now out of ideas. Any help would be appreciated.
Beyond the SQL injection mentioned above by DaveRandom take a look at the php manual on how setcookie works:
http://php.net/manual/en/function.setcookie.php
It mentions specifically the info is injected into the headers, and therefor not available until your next page load. You probably want to do something like
if(isset($_COOKIE['deceasedID']))
{
$deceasedID = $_COOKIE['deceasedID'];
}
else
{
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
$deceasedId = $row['PK_Deceased'];
}

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