I want to add "update", "delete" and "view" in the other page button in the right side of the table rows of my php table. Please help me to add it. Here is my code:
<?php
$conn = mysqli_connect('localhost','root','','dbname');
if(mysqli_connect_errno()){
echo 'Failed to connect: '.mysqli_connect_error();
}
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo '</tr>';
}
echo '</table>';
mysqli_close($conn);
?>
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Actions</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
Update
Delete
View
</td>";
echo '</tr>';
}
echo '</table>';
You should use jquery/Ajax for delete. It is better option.
For delete write this function: Need to add min jquery file
<script src="js/jquery-1.7.1.min.js"></script>
<script>
function deleteRow(id)
{
$.ajax({
url: 'delete.php',
type: "POST",
data: {
'id' : id,
},
success : function(response) {
alert('Record deleted');
},
error : function() {
},
complete : function() {
}
});
}
</script>
write your delete record code in 'delete.php'.
This is one option. You can do this in more good and specific way. Everything to say here is not possible for me.
for view you can do this in two ways.
1) If you want to display in same format, redirect it on self page and put condition like.
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
else
{
$query = "SELECT * FROM table";
}
2) If you want in different format, Do same thing in view.php select only that record.
One simple thing i want to ask what is the need for view? when it is already in table above.
For Update write in your update.php :
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
and set form action
<form method="post" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
fetch value of above result in input box like and also fetch id as hiiden field:
<input type='text' name='firstname' value='<?php echo $row['firstname']; ?>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>
and for update you can go like:
if(isset($_POST['firstname'] && isset($_POST['lastname'] ) // Here you can use your any required field
{
//Your update logic go here like:
$id = $_POST['id'];
$query = "UPDATE table SET firstname=$_POST['firstname'] where id=$id"; // Your whole update query.
}
i see some mistake in your code:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
should be:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$query);
try this
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th></th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
<input type='submit' value='update'>
<input type='submit' value='delete'>
<input type='submit' value='view'>
</td>";
echo '</tr>';
}
echo '</table>';
Try this functions:
<?php
Class Db {
protected $connection;
public function __construct() {
$this->connection = $connection;
}
function insert($table,array $data) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$fields.= $col.",";
}
foreach($data as $col => $value) {
$values.= "'".replace_str($value)."',";
}
$fields = substr($fields,0,-1);
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"insert into ".$table."(".$fields.") values(".$values.")")) {
HandleDBError("Error inserting data to the table\query:$query");
}
return $query;
}
function update($table, array $data, $where) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$values.= $col."='".replace_str($value)."',";
}
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"update ".$table." set ".$values." where ".$where)) {
HandleDBError("Error updating data to the table\query:$query");
}
return $query;
}
function delete($table, $where = '') {
if ($where)
return mysqli_query($this->connection,"delete from ".$table." where ".$where);
return mysqli_query($this->connection,"delete from ".$table);
}
function get($strQuery) {
if(!$query = mysqli_query($this->connection,$strQuery)) {
HandleDBError("Error inserting data to the table\query:$query");
}
$data = [];
while($row = mysqli_fetch_assoc($query)) {
$data[] = $row;
}
return $data;
}
}
?>
Related
Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,
Below is my code. I have two MySQL database tables, one is "member" and another one is "participants". I would like to display the data in table "member" to my local host page and I did it. However, I cannot insert multiple rows of "member" data by using checkbox to my database table "participants". I am stuck. Any help is much appreciated.
<?php
try {
$con = new PDO("mysql:host=localhost;dbname=kgruum member", "root", "");
$sql = $con->query("SELECT * FROM member");
echo "<table class='info' align='center' border='1'>";
echo "<tr><td width='10'></td>
<td width='10'><b>ID</b></td>
<td width='500'><b>Name</b></td>
<td width='50'><b>Handicap</b></td><tr>";
foreach($sql as $row) {
$ID = $row["ID"];
$Name = $row["Name"];
$Handicap = $row["Handicap"];
echo "<tr>
<td><form method='POST' action='Add participant.php'><input type='checkbox' name='insert[]' value='$ID'></td>
<td>$ID</td>
<td>$Name</td>
<td>$Handicap</td><tr>";
}
echo"</table><div align='center'><input type='image' value='submit' src='add selected button.png' alt='submit Button' onmouseover='this.src='pink add selected button.png'' onmouseout='this.src='add selected button.png'' name='add_btn' id='add_btn'></div><br></form>";
if(isset($_POST['add_btn'])) {
if(!empty($_POST['insert'])) {
foreach($_POST['insert'] as $check) {
$st=$con->prepare("INSERT INTO participants(ID,Name,Handicap) VALUES('$ID','$Name','$Handicap')");
$insert->bindParam('ID',$ID);
$insert->bindParam('Name',$Name);
$insert->bindParam('Handicap',$Handicap);
$st->execute();
}
echo "<script type='text/javascript'>
alert('Successful Insert ! ');
window.location.href = 'Add participant.php';
</script>";
} else {
echo "<script type='text/javascript'>alert('You didn't choose which user you want to insert ! ')</script>";
}
}
} catch(PDOException $e) {
echo "error".$e->getMessage();
}
?>
You are not storing the $Name and $Handicap values in the insert[] array, you only storing the $ID value.
To resolve, do something like this:
<input type='checkbox' name='insert[]' value='$ID|$Name|$Handicap'>
Then:
foreach($_POST['insert'] as $check) {
$values = explode('|', $check);
$ID = $values[0];
$Name = $values[1];
$Handicap = $values[2];
//The rest of your SQL code goes here as you have it...
$check = '';
}
TABLE.PHP - Table is correctly displaying. I just posted important codes here.
$ipn="192.168.196.";
echo "<form method ='post' action='class_prdsbmt.php'>";
echo "<table border='5'>";
echo "<td>";
echo "<table name='' border='3'>";
for($a1=51;$a1<68;$a1++){
for($a2=52;$a2<70;$a2++){
echo "<tr>";
echo "<td><input type='hidden' value='".$ipn.$a1."' name='td_a[]' />$ipn$a1</td>";
echo "<td><input type='hidden' value='".$ipn.$a2."' name='td_a[]' />$ipn$a2</td>";
echo "</tr>";
$a1+=2;
$a2+=1;
}
echo "</table>";
echo "</td>";
}
echo "<td><input type='submit' value='PRINT' name='btnss' /></td>";
class_prdsbmt.php
include("class_prdtrans.php");
$pcs = $_POST['td_a'];
for ($i = 0; $i < ; $i++) {
$arr=$pcs[$i];
$printval = new PrintVal($arr,"TESTING ONLY");
$crud = new CRUD_process();
}
<?php
if(isset($_POST['btnss'])){
$isSuccess=0;
$strCol = "pcip,pcname";
$strVal = "'".$printval->getIp()."','". $printval- >getPcname()."'";
$isSuccess = $crud->saveRecord("machine",$strCol,$strVal);
}else{
"NOT SAVED! GO BACK!!!";
}
?>
class_prdtrans.php
define('DB_SERVER','localhost');
define('DB_USER','user');
define('DB_PASSWORD','');
define('DB_NAME','db');
class PrintVal{
var $_ipmac;
function __construct($ipmac,$namemac){
$this->_ipmac = $ipmac;
}
function getIp(){
return $this->_ipmac;
}
}
//crud operation
class CRUD_process{
var $con;
function __construct(){
$this->con = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME);
}
function saveRecord($record,$columns,$values){
$result = false;
switch($record){
case "machine":
$result = $this->con->query("INSERT INTO tbl (".$columns.") VALUES(".$values.");");
break;
default:
}
return $result;
}
function getRecord($record,$values){
$result = false;
$val = explode(",",$values);
switch($record){
case "machine":
$result = $this->con->query("SELECT * FROM tbl WHERE pcip =".$val[0]." AND pcname = ".$val[1].";");
break;
default:
}
return $result;
}
}
Try to echo the INSERT query and the output is wrong. First field(pcip) values are null. Below is the SQL output.
INSERT INTO tbl (pcip,pcname) VALUES('','TESTING ONLY');
Please help me to come-up for a better way or simplest way to insert all array values of 'td_a[]' from a table to be inserted into my database once I click the button.
in class_prdsbmt.php
for ($i = 0; $i < ; $i++) {
$arr=$pcs[$i];
$printval = new PrintVal($arr,"TESTING ONLY");
$crud = new CRUD_process();
}
$i < ????, also you created so many obj CRUD for nothing. move it to if(isset condition below
hi friends i'm creating a php page to import the data from a csv file into sql database..
here database table and number of fields are specified by user itself..
if user specifies 4 fields, then it is created using a for loop as follows..
<?php
include('connect.php');
$name = $_POST['table_name'];
//echo $name;
$create_tab = "CREATE TABLE $name(id varchar(15) PRIMARY KEY)";
if(mysql_query($create_tab,$con))
{
echo "Table <b><i>$name</i></b> created successfully... <br/> <br/>Add columns...";
}
else {
die('Error1'.mysql_error());
}
$field = $_POST['number_of_fields'];
//echo $name.$field;
echo '<form id="form1" name="form1" method="post" action="update-table.php">';
echo "<p>
<label for='tablename'></label>
<input type='hidden' name='tablename' id='tablename' value='$name' size='5'/>
</p>";
echo "<p>
<label for='fields'></label>
<input type='hidden' name='fields' id='fields' value='$field' size='5'/>
</p>";
echo '<table border="1" cellpadding="5" cellspacing="5">';
for ( $i = 1; $i <= $field; $i ++) {
echo '<tr>';
echo '<td>';
echo "<p>
$i
</p>";
echo'</td>';
echo '<td>';
echo "<p>
<label for='textfield$i'></label>
<input type='text' name='field$i' id='textfield$i' />
</p>";
echo'</td>';
echo '<td>';
echo "
<select name='select$i' id='select$i'>
<option value='varchar(200)'>varchar</option>
<option value='int'>int</option>
<option value='float'>float</option>
<option value='date'>date</option>
</select>";
echo '</td>';
echo '</tr>';
}
echo '</table>';
?>
<p>File Location :
<input type="text" name="fileField" id="fileField" />
</p>
<br/>
<INPUT type="image" name="search" src="images/alter.gif" border="0" height="75" width=120">
</form>
then table create and alter as follows..
<?php
include('connect.php');
$field = $_POST[fields];
$name = $_POST[tablename];
for ( $i = 1; $i <= $field; $i++) {
//getting field names
$varname = ($txtfield . $i);
$$varname = $_POST[field.$i];
// echo $$varname;
$fi = $$varname;
//getting field types
$selname = ($selfield . $i);
$$selname = $_POST[select.$i];
$dt = $$varname;
$sql = "ALTER TABLE $name ADD $fi $dt";
if(mysql_query($sql,$con))
{
echo "Field <b><i>$fi</i></b> added successfully...<br/>";
}
else {
die('Error1'.mysql_error());
}
}
?>
as above database table and fields are crated...
i got the concept of inserting data using static variables as follows..
<?php
// data import
include('connect.php');
$field = $_POST['fileField']; //file directory
echo "<br/><br/>Import file path: ";
echo $field;
$file = $field;
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
// ' escape character
if (strpos($column2, "'") == FALSE)
{
$column21 = $column2;
}
else{
$column21 = str_replace ("'", "\'", $column2);
}
$column3= $arr[2];
$column4= $arr[3];
//print data from csv
echo "<table border='1' width='800' cellpadding='5' cellspacing='2'>";
echo "<tr>";
echo "<td width='8'>";
echo $column1;
echo "</td>";
echo "<td width='100'>";
echo $column21;
echo "</td>";
echo "<td width='5'>";
echo $column3;
echo "</td>";
echo "<td width='5'>";
echo $column4;
echo "</td>";
echo "</tr>";
echo "</table>";
$import="INSERT into $name (id,name,year1,year2) values(
'$column1','$column21','$column3','$column4')";
mysql_query($import) or die(mysql_error());
}
?>
now, my question is how can i make this insert statement dynamic as such it creates field names and values dynamically inside insert query from the data obtained from for loop in table create and alter query???
If I understand your question correctly, it sounds like you want to combine your inserts into one query (which is very smart performance wise). SQL allows you to insert multiple rows at once like so:
INSERT INTO table (id, first, last) VALUES(NULL, 'Ryan', 'Silvers'),(NULL, 'Oscar', 'Smith'),(NULL, 'Jessica', 'Owens')
So by using creating an array of VALUES and using implode to join them you can make one query:
//Create rows
foreach($rows as $row) {
$queryRows[] = "(NULL, '".$row['first']."', '".$row['last']."')";
}
//Create query
$query = 'INSERT INTO table (id, first, last) VALUES'.implode(',', $queryRows);
Now that I understand your real question, I can give you a basic overview of what you need to do to achieve this. You need to create a form that allows a user to enter data that will be inserted into the table.
<form method="post" action="process.php">
<input name="field1" />
<!-- and more -->
</form>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
<?php
//Check form submission and validate entries, then...
$stmt = $pdo->prepare('INSERT INTO table (field1) VALUES(:field1)');
$stmt->execute(array(':field1', $_POST['field1']));
?>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
function insert($tablet,$datad)
{
if(empty($tablet)) { return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$query1 = "select * from user";
$result1 = mysql_query($query1);
$numcolumn = mysql_num_fields($result1);
$addd = "";
$count = 0;
for ( $i = 1; $i < $numcolumn; $i++ )
{
$columnnames = mysql_field_name($result1, $i);
if(($numcolumn-1) == $i)
{
$addd .= $columnnames;
$data .= "'".$datad[$count]."'";
}
else
{
$addd .= $columnnames.",";
$data .= "'".$datad[$count]."',";
}
$count++;
}
$ins = "INSERT INTO ".$tablet."(".$addd.")"."VALUES(".$data.")";
mysql_query($ins);
header('Location: index.php');
exit;
}
as the title states I am trying to write a code that will update a boolean data in column (I called 'status') for a specific row. I used while loop in table to display the rows of new registered and where the status is NULL, I've put two buttons (accept, reject) each in td so they'll be displayed to each name, What I want is when the accept button clicked, it sets the status of its row in the table to 1, and when reject is clicked, same thing but sets 0 instead of 1.
I've did a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks!
Here is my code:
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc".$i."'>Accept</button></td>";
echo "<td><button name='sRej".$i."'>Reject</button></td>";
echo "</tr>";
$i++;
}
if (isset($_POST['sAcc'.$i])) {
$row['status'] = 1;
}
}
getStudent();
?>
</table>
First of all, you miss <form> element. Your form inputs are useless without it, or without ajax.
Secondly, your $_POST check will only check last item. Since after you exit loop $i is set to last value in the loop. So your example will only work on last item.
<button> will now send $_POST with one of indexes sAcc or sRej. And it's value will be ID of your entry.
<table id="sHold" style="border:none;">
<form method="post" action="">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>{$sId}</td>";
echo "<td>{$sName}</td>";
echo "<td><button type='submit' name='sAcc' value='{$sId}'>Accept</button></td>";
echo "<td><button type='submit' name='sRej' value='{$sId}'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
if (isset($_POST['sAcc']) && intval($_POST['sAcc'])) {
$user_id = (int) $_POST['sAcc'];
// Do the database update code to set Accept
}
if (isset($_POST['sRej']) && intval($_POST['sRej'])) {
$user_id = (int) $_POST['sRej'];
// Do the database update code to set Reject
}
getStudent();
?>
</form>
</table>
Tip: I assume you're beginner. I remade your code. But you dont need to put this code into function. Use functions to handle data retrieval for example. Dont use it to display html.
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table where status='NULL'";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['name'];
echo "<tr id='".$sId."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc' id='acc-".$sId."' onclick='approveuser(this.id)'>Accept</button></td>";
echo "<td><button name='sRej' id='rec-".$sId."' onclick='approveuser(this.id)'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
getStudent();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function approveuser(id){
trid=id.split('-')[1];
//alert(trid);
$.ajax({
url: "update.php",
type:"post",
data:{ val : id },
success: function(result){
//alert(result);
$('table#sHold tr#'+trid).remove();
alert('Updated');
}
});
}
</script>
//The code give below this update.php pge(ajax page)
<?php
$data=$_POST['val'];
$status =explode('-',$data);
$user_id=$status[1];
if($status[0]=='acc'){
$value=1;
}
elseif($status[0]=='rec'){
$value=0;
}
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
mysqli_query($conn,"update student_table set status='$value' where student_id=$user_id");
?>