Update in php using sql and phpmyadmin - php

I am trying to create an update form to update to the database table. I have created a function that uses sql to create the update, and a function that updates the table. I have also created the code that calls these functions. The error is that nothing is posting or changing when I press submit. It isn't running or editing or updating any of the data.
Please help me get this code working!
Thanks
function updateSingleValue($ID, $Name)
{
$sql = "UPDATE faculty SET Name=$Name WHERE ID=$ID";
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
$bReturn = false;
try
{
$statement->execute();
$bReturn = true;
}
catch (PDOException $e)
{
echo $e->getMessage();
}
return $bReturn;
}
function getUpdateResults($tablename)
{
$mysqlConnection = getConnection();
$sql = "SELECT * FROM ".$tablename;
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
<?php
include_once 'db.php';
if(isset($_POST['update']))
{
$success = updateSingleValue($_POST['ID'], $_POST['Name'], $_POST['update']);
echo $success;
if(!$success)
{
echo 'Sorry, the update failed.';
}
}
$Results = getUpdateResults('faculty');
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<label id="lblUpdate" for="update">Update</label>
<input type="text" name="update" />
<input type="text" name="ID" />
<input type="text" name="Name" />
<input type="submit" name="submit" value="Submit"/>
</form>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<?php
if(isset($Results))
{
foreach($Results as $row)
{
echo '<tr><td>';
echo $row['ID'];
echo '</td><td>';
echo $row['Name'];
echo '</td></tr>';
}
}
?>
</table>

Iv'e noticed something with this:
function getUpdateResults($tablename)
{
$mysqlConnection = getConnection();
$sql = "SELECT * FROM ".$tablename;
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
try doing concatinating your tablename like this
$t = $tablename;
$sql = "SELECT * FROM $t";

Please close the open connection at the end....
mysql_close($mysqlConnection);

Related

Updating SQLite database with PHP

I have been working on this problem for the past 3 or 4 hours. I have an SQLite database which interacts with PHP. So far, I have been able to perform 3 of the 4 CRUD operations. The only one which won't work is the the U part (update). I am able to print data into my form, but clicking on the submit button will just make the app hang for some time until I get a custom error message from my app. Also, the record doesn't get updated.
Your help is very much appreciated!
Here is my current code for the edit/update form and page from my app:
<?php
// $db->close();
// echo $_GET['id'];
?>
<!-- get database content -->
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_GET, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<!-- print database content -->
<?php
// has the form been submitted?
// if not, show the HTML form
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF'] . "?id=" . $r['id']); ?>" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required value="<?php echo htmlspecialchars($r['sname']); ?>">
<label for="score">Score</label>
<input type="number" name="score" required value="<?php echo htmlspecialchars($r['score']); ?>">
<button type="submit" name="submit">Submit</button>
</form>
<!-- update database content -->
<?php
} else {
try {
$id = $_POST['id'];
$db = new PDO("sqlite:database.db");
// print out error messages is something goes wrong
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE students_tb SET sname = :sname, score = :score WHERE id = $id";
// UPDATE table_name
// SET column1 = value1, column2 = value2...., columnN = valueN
// WHERE [condition];
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been updated in the database.";
echo "<p><a href='/'>Go back to the main page.</a></p>";
} else {
echo "The student has NOT been updated in the database.";
echo "<p><a href='/'>Go back to the main page.</a></p>";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
After browsing your source files, it is found that the record will be locked because you are doing the select and then doing the update immediately (which is of course not necessary, in all cases).
Hence, Please use the following code to fix the problem (I have included a hidden field known as actionx to prevent the PHP to do both select and update at the same time) :
So for the edit.php, it should be:
<?php
// $db->close();
// echo $_GET['id'];
?>
<?php if ($_REQUEST["actionx"] =="") { ?>
<!-- get database content -->
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_POST, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<form action="edit.php" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required value="<?php echo htmlspecialchars($r['sname']); ?>">
<label for="score">Score</label>
<input type="number" name="score" required value="<?php echo htmlspecialchars($r['score']); ?>">
<input type=hidden name=id value="<?php echo $_REQUEST["id"]; ?>">
<input type=hidden name=actionx value="update">
<button type="submit" name="submit">Submit</button>
</form>
<?php } ?>
<?php if ($_REQUEST["actionx"] !="") { ?>
<?php
try {
$id = $_POST['id'];
$db = new PDO("sqlite:database.db");
// print out error messages is something goes wrong
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE students_tb SET sname = :sname, score = :score WHERE id = :id";
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$id = filter_input(INPUT_POST, "id");
$stat->bindValue(":id", $id, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been updated in the database.";
echo "<p><a href='index.php'>Go back to the main page.</a></p>";
} else {
echo "The student has NOT been updated in the database.";
echo "<p><a href='index.php'>Go back to the main page.</a></p>";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
On the other hand, for the one.php (displaying a single record), please use this:
<?php
echo $_GET['id'];
?>
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_GET, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<h1><?php echo htmlspecialchars($r['id']); ?></h1>
<p>Description: <?php echo htmlspecialchars($r['sname']); ?></p>
<p>Score: <?php echo htmlspecialchars($r['score']); ?></p>
<form action="<?php echo 'delete.php?id=' . htmlspecialchars($r['id']) ?>" method="POST">
<button type="submit" name="delete">Delete this record</button>
</form>
<form action="edit.php" method="POST">
<button type="submit" name="delete">Edit this record</button>
<input type=hidden name=id value="<?php echo $r['id']; ?>">
</form>

PHP PDO output in angular

I am trying to get output in Angular via PHP PDO but unable to understand the error.
When I write the same code using PHP procedural way (mysqli) then I can easily fetch the output. But I am struggling in fetching data with PHP PDO.
Here is my code:
Index.php:
<div ng-app="myapp" ng-controller="fieldcontroller" ng-init="displayData()">
<tr ng-repeat="field in fields">
<td>{{ field.fieldlabel }}</td>
</tr>
My JS File:
var app = angular.module("myapp",[]);
app.controller("fieldcontroller", function($scope, $http){
//Display Function
$scope.displayData = function(){
$http.get("model/select.php?type=getForm")
.then(function(response) {
$scope.fields = response.data;
console.log($scope.fields);
});
}
});
PHP File:
?php
//include('Database.php');
//select.php
//$connect = mysqli_connect("localhost", "kcmsuser", "KC+wSH&X#z9P", "kcms");
$server = 'localhost';
$user = 'kcmsuser';
$pass = 'KC+wSH&X#z9P';
$dbname = 'kcms';
$conn = new mysqli($server, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo " Connected successfully ";
}
$sql = "SELECT * FROM form";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$output = array();
while($row = $result->fetch_array()) {
$output[] = $row;
}
} else {
echo "0 Results ";
}
echo json_encode($output);
Console.log shows:
[{"0":"110","id":"110","1":"First Name","fieldlabel":"First Name","2":"firstname","fieldname":"firstname","3":"text","fieldtype":"text","4":"","isprimary":"","5":"yes","required":"yes","6":"1","position":"1"},{"0":"23","id":"23","1":"Carrier","fieldlabel":"Carrier","2":"carrier","fieldname":"carrier","3":"text","fieldtype":"text","4":"no","isprimary":"no","5":"yes","required":"yes","6":"5","position":"5"},{"0":"26","id":"26","1":"Email","fieldlabel":"Email","2":"email","fieldname":"email","3":"email","fieldtype":"email","4":"","isprimary":"","5":"yes","required":"yes","6":"9","position":"9"},{"0":"27","id":"27","1":"Password","fieldlabel":"Password","2":"password","fieldname":"password","3":"password","fieldtype":"password","4":"","isprimary":"","5":"no","required":"no","6":"4","position":"4"},{"0":"102","id":"102","1":"Date of Birth","fieldlabel":"Date of Birth","2":"dob","fieldname":"dob","3":"date","fieldtype":"date","4":"","isprimary":"","5":"no","required":"no","6":"6","position":"6"},{"0":"101","id":"101","1":"Last Name","fieldlabel":"Last Name","2":"lastname","fieldname":"lastname","3":"text","fieldtype":"text","4":"","isprimary":"","5":"yes","required":"yes","6":"2","position":"2"}]
And [ngRepeat:dupes] warning.
I tried track by $index with ng-repeat but nothing happens.
I am new to Angular.
you can use pdo code for get data from mysql
<?php
$servername="localhost";
$username="";
$password="";
$dbname="";
$dsn="mysql:host=$servername;dbname=$dbname";
try{
$connect=new PDO ($dsn,$username,$password);
$connect->exec("SET NAMES 'utf8';");
}catch(PDOException $error){
echo "Error in connect".$error->getMessage();
exit();
}
$sql = "SELECT * from `table`";
$result = $connect->query($sql);
$num_row=$connect->query("SELECT count(id) from `table`")->fetchColumn();
if ($num_row > 0) {
$output = array();
while($row=$result->fetch(PDO::FETCH_ASSOC)) {
$output[] = $row;
}
} else {
echo "0 Results ";
}
?>
After spending few hours and hit and try message, I was able to sole the problem.
Problem was in the below PHP code:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo " Connected successfully ";
}
Thanks....
sorry i was busy, i write code for you very fast if you have any proplem you can say me
<?PHP
if(#$_REQUEST['delete']){
/**************delete**************/
$delete=$_REQUEST['delete'];
if($connect->query("delete from table where id='$delete'")){
echo 'delete successful';
}}else if(#$_REQUEST['insert']=='record'){
/**************insert**************/
if(isset($_POST['submit'])){
$title=$_POST['title'];
if($connect->query("INSERT INTO `table`(`title`) VALUES ('$title')")){
echo 'success'; }else{ echo 'error'; }
}}else if(#$_REQUEST['edit']=='record'){
/**************insert**************/
if(isset($_POST['submit'])){
$title=$_POST['title'];
$mid=$_POST['mid'];
if($connect->query("UPDATE `table` SET `title`='$title'")){
echo 'success'; }else{ echo 'error'; }
}} ?>
<h1><?PHP if(#$_REQUEST['edit']=='new'){?>insert<?PHP }else if(#$_REQUEST['edit']=='new'){?>edit<?PHP }else{?>manage<?PHP }?><h1>
<br>insert
<?PHP
if(#$_REQUEST['edit']=='new'){
$id=$_REQUEST['id'];
$checks=$connect->query("select * from table where id='$id' order by id desc");
$check=$checks->fetch(PDO::FETCH_ASSOC);
?>
<form>
<input type="text" name="title" value="<?=$check['title']?>">
<input type="hidden" name="edit" value="record">
<input type="hidden" name="mid" value="<?=$check['id']?>">
<input type="submit" value="edit" name="submit"/>
</form>
<?PHP }else if(#$_REQUEST['insert']=='new'){?>
<form>
<input type="text" name="title">
<input type="hidden" name="insert" value="record">
<input type="submit" value="create" name="submit"/>
</form>
<?PHP
}else{
$radif=0;
$qacs=$connect->query("select * from table order by id desc");
while ($qc=$qacs->fetch(PDO::FETCH_ASSOC)){$radif++;
?>
<tr>
<td scope="row"><?=$radif?></td>
<td><?=$qc['title']?></td>
<td>delete</td>
<td>edit</td>
<?PHP }}?>

how to display the mobile no in mobile no label searching by employee id in html using php and mysql

I want to display the mobile number in mobileNo label but when I enter the employee id for search this code displays no result.
I want to display data using the while loop in my html form
search.php
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search = $mysqli->real_escape_string(isset($_POST['search']));
$resultSet = $mysqli->query("SELECT * FROM emp WHERE emp_id = '$search'");
if($resultSet->num_rows > 0)
{
while($rows = mysqli_fetch_row($resultSet))
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}
{
$output = "No result";
}
}
?>
display.php
<html>
<head>
</head>
<body>
<form action="search.php" method="post">
<ul>
<li>
<label for="employeeId">Employee Id</label>
<input type="text" name="employeeId" placeholder="Employee Id" />
<input type="submit" value="search" name="search"/>
</li>
<li>
<label for="mobileNo">Mobile No.</label>
<?php echo $output;?>
</li>
</form>
</body>
</html>
1st : you missed else That's why $output variable alwasy overwrite by No result .
2nd : $search = $mysqli->real_escape_string(isset($_POST['search'])); this line wrong isset will return boolean value your escaping for boolean value .
3rd : Try to use prepared statement to avoid sql injection .
PHP:
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search=$_POST['search'];
$stmt = $conn->prepare("SELECT * FROM emp WHERE emp_id = ?");
$stmt->bind_param('i',$_POST['search']);
$stmt->execute();
$get_result = $stmt->get_result();
if($get_result->num_rows > 0)
{
while($rows = $get_result->fetch_assoc())
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}else //here else missed .
{
$output = "No result";
}
}
?>
<?php
$output = NULL;
$mysqli = mysqli_connect("localhost","root","","db") or die ("Error in connection");
if(isset($_POST['search']))
{
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM emp WHERE emp_id = '$search'");
if($resultSet->num_rows > 0)
{
while($rows = mysqli_fetch_assoc($resultSet))
{
$mobileNo = $rows['emp_mob_no'];
$output = "Mobile no: $mobileNo";
}
}
else
{
$output = "No result";
}
}
?>

function running in foreach loop

thank you for taking time to look at this. I have been dealing with this annoying foreach loop. Here is what I am trying to do.
I have the first page "form.php".
On this page I have check boxes. Each check box is generated from a database table. Here is the code:
<?php
include("config.php");
$mysqli = new mysqli($host, $db_uname, $db_pass, $db);
$query = "SELECT * FROM `plugins` WHERE 1";
if ($result = $mysqli->query($query)) {
echo '<form action="test.php" method="post">
<input name="gname" placeholder="Group Name..."/>
<table width="200">
';
while ($row = $result->fetch_assoc()) {
echo '<tr><td>
<label>
<input type="checkbox" value="'.$row["plugin"].'" name="checkbox[]">
'.$row["plugin"].'
</label>
</td></tr>';
}
echo '
</table>
<select name="permplugin">
<option>Select One...</option>';
$query2 = "SELECT * FROM `permission_types` WHERE 1";
if ($result2 = $mysqli->query($query2)) {
echo '<h3>Select Permission format below</h3><hr />';
while ($row2 = $result2->fetch_assoc()) {
echo '
<option value="'.$row2["plugin_name"].'">'.$row2["plugin_name"].'</option>';
}
echo '
</select>
<br />
<input name="" type="reset"><input name="" type="submit">
</form>';
}
}
?>
Now after that it sends the checked boxes to "test.php"
here is the code for that:
<?php
if(!empty($_POST['checkbox']) || !empty($_POST['select']) || !empty($_POST['gname'])) {
echo '<h1>'.$_POST['gname'].'</h1>';
$check1 = $_POST['checkbox'];
foreach($check1 as $check) {
include "functions.php";
checkboxes($check);
}
echo '<h3>Selected Permission format below</h3><hr />';
echo $_POST['permplugin'];
} else {
echo "please select atleast one plugin.";
}
?>
The functions page code looks like this:
<?php
//all functions are here.
function checkboxes($check){
$mysqli_perm = new mysqli("localhost", "uname", "pword", "tcordero_permnodes");
$query_perm = "SELECT * FROM permission_nodes WHERE plugin = `$check`";
if ($result_perm = $mysqli_perm->query($query_perm)) {
echo $check;
/* fetch associative array */
while ($row_perm = $result_perm->fetch_assoc()) {
echo $row_perm['node'].'<br />';
}
unset($check);
}
}
When I run the test.php I get this error:
Fatal error: Cannot redeclare checkboxes() (previously declared in C:\xampp\htdocs\TPYC\functions.php:3) in C:\xampp\htdocs\TPYC\functions.php on line 15
What am I doing wrong?
You need to take the include out of the foreach loop. Try this:
include "functions.php";
foreach($check1 as $check) {
checkboxes($check);
}

Deleting Multiple Records using Checkboxes in PHP

I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>

Categories