I have a page with 3 columns, the first 2 columns have forms while the third shows information.
Whenever the page is called, information corresponding to the first form will already exist, however the second form can be used to insert new data or update existing.
The code I have at the moment:
<?php
require_once 'connect.php';
$formType = $_POST['formType'];
$id = $_POST['id'];
$favColor= $_POST['favColor'];
$favFood= $_POST['favFood'];
$country = $_POST['country'];
if($_POST['formType'] == 'guestCosts'){
$sth = $dbh->prepare("INSERT INTO info (id, favColor, favFood, country)
VALUES ('$id', '$favColor', '$favFood', '$country')");
$sth->execute();
}elseif($_POST['formType'] == 'guestCosts'){
$sth = $dbh->prepare("UPDATE info SET favColor = '$favColor', favFood = '$favFood', country = '$country' WHERE id = '$id'");
$sth->execute();
}
$dbh =null;
?>
The problem I'm having is that I see now way to distinguish between when I should do an UPDATE vs when I should do an INSERT.
The page that generates the form does a query to populate the form with the values from the database. I thought of adding a hidden field if the database is empty for a particular id for example:
<input type = "hidden" name ="action" value="insert" />
However I'm not sure passing a variable between pages is the most efficient way. Is there a better way to do what I am trying to do?
Take a look at MySQL INSERT ON DUPLICATE KEY UPDATE
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Related
<?php
$sql = "SELECT * FROM team;";
$result = mysqli_query($conn, $sql );
$row = mysqli_fetch_row($result);
$teamname = $row[1];
echo $teamname;
Consider table in DB consists of 10 names from 1-10. That will be displayed on the screen as usually (using retrieving), but the problem is when I click any name from 1-10 displaying on the screen that should open a new page by displaying only the particular name I selected.
I tried this but, all the values are displaying.
First, add to your mysql table a column called "ID" to associate a number to each name.
After you can direct the user to your page like this
Name n.1 // etc..
so you can take the id of your name using GET and display to your page only that name
(Always use Prepared Statement even when it is not strictly necessary)
PHP script
$name_id = $_GET['id'];
// connect to your db
$stmt = $db->prepare("SELECT * FROM team WHERE ID = ?");
$stmt->bind_param("s",$name_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
echo $result['name'];
if you need anything else, comment below.
An html form is part of the code which l have intentionally decided not to include. Here is a snapshot of my code:
<?php
require('db.php');
$id=$_REQUEST['id'];
$query = "DELETE FROM new_record WHERE id=$id";
$result = mysqli_query($con,$query) or die ( mysqli_error());
header("Location: view.php");
?>
I don't know if you have an auto incrementing primary key column in your table, but its best if you have one so you can easily update individual records
First you will need to change your SELECT query (or run a new one) and set a WHERE clause to select database entry.
Then change the INSERT script to this:
$insert = $db->prepare("UPDATE people SET firstName = ?, lastName = ?, bio = ? WHERE ID = ?");
$insert->bind_param('sssi', $firstName, $lastName, $bio, $id);
Where $id is the id of the entry in your 'people' database that you got from the SELECT query you ran earlier.
For edit you to have to make a logic, like make this
<td><input type="button" class="btn-info" name="btn" value="Edit"></td>
to a href,
<td>Edit</td>
Supposing id as primary key, and on this new page make a edit form, save it and redirect here.
I'm trying to update MySQL table recored by any calculated form values in php, but it doesn't work. May you help me please thank you.
You should use mysqli with prepared statements, like so.
I hope this is enough for you, you gave me nothing to work with so...
<?php
//Get the form value and ID of the database record to update
$value = $_POST['value']; // Value submitted by a form element (replace this with whatever you want to change)
$id = $_POST['id']; //ID, could be of the user etc. (this will be a primary key inside the database) (does not have to be submitted via POST, I assume you know this already)
//Establish a new mysql connection
$mysqli = new mysqli($db_host,$db_user,$db_pass,$db_name);
//Set up a query
$query = "UPDATE table SET column_one=? WHERE id=?";
//Prepare the statement
$stmt = $mysqli->prepare($query);
//Bind the parameters
// 'si' = in the order of submitted valurs (column_one=? and id=?) (column_one is s and id is i, s is for string, i is for integer) (this defines what types of variables we are sending)
$stmt->bind_param('si', $value, $id);
//Execute the query
if($stmt->execute()){
//Get the amount of affected rows
$affected = $stmt->affected_rows(); //Should only be 1, but if your ID or whatever you're using to define which parts of the DB to update is not unique, then it can go higher ofc.
//Show success
echo "Database updated, $affected rows affected";
}else{
//Show error
echo "Error, say that this is shown, on stack overflow, as there's obviously something wrong.";
}
//Close the stmt/mysqli stuff
$stmt->close();
$mysqli->close();
I'm currently creating some sort of inventory system.
I have master_tbl where in I save the items. In master_tbl, I have column qty_left or the available stock left.
I also have the table issuance_tbl where in I save all the transaction in issuing items.
In this table there is issued_qty.
My problem is how can I INSERT a row into issuance_tbl at the same time UPDATE the master_tbl.qty_left. (master_tbl.qty_left - issuance_tbl.issued_qty).
Is it possible?
I think the best way is using Stored Procedure. You can have bunch of SQL statements with error handling and ACID transactions in one place. This is because if your first query executes and the second fails, you may need to rollback transactions. Stored procedures allow all this fancy but reliable stuff.
You can start here: http://forums.mysql.com/read.php?98,358569
I'm not completely confident that 'If there's any way to do such thing':
You need to do it in steps, LIKE THIS:
$result = $this->db->insert($table);//Example function to insert inventory item
$insert_id = $this->db->insert_id();//Example function to get the id of inserted item
if($result)
$res = $this->db->update($id,$data,$table);//Example function to update data of quantity table
if(!$res)
{
$this->db->delete($insert_id,$table);s
$result = '-1';
}
return $result;
Hope this might help
here is the example:
<form method="post">
QTY:<input type="text" name="qty_left"></input>
<input type="submit" name="submit" value="update"></form>
<?php
////////your config db
$qty = $_POST['qty_left'];
if(isset($_POST['submit']);
$sql = mysql_query("insert into issuance_tbl (issued_qty) values (".$qty.") ");
$sql1 = mysql_query("update master_table set qty_left= ".$qty."");
?>
$con = mysqli_connect($host, $user, $password, $database);
...
$issued_qty = '10'; //some value
$insert_query = "insert into issuance_table (issued_qty, ...) values ('$issued_qty', ... ) ;";
$update_query = "update master_tbl set qty_left = (qty_left - ".$issued_qty.") where ....";
mysqli_multi_query($con, $insert_query.$update_query);
I'd like to insert data into a table only when certain values in that table's (sessionid) row match another variable. I am struggling to put together the INSERT statement. The approach I am taking: retrieve all the rows in the table that match the criteria (retailer=$retailer) and then iterate through those rows inputting the variable options into the sessionid table.
$retailer = $_GET['retailer'];
$options = $_GET['options'];
$session = session_id();
//mysql connection stuff goes here
$query = "
SELECT *
FROM `sessionid`
WHERE `retailer` = '$retailer'
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
mysql_query("INSERT INTO sessionid (options) VALUES('$options')");
}
Is the syntax correct for me to do this? Thanks!
Are you maybe looking for the UPDATE command instead?
UPDATE sessionid
SET options = $options
WHERE retailer = $retailer
By the way, I would look in to using PDO as it's more secure than pushing $_GET values in a database.
$db = new PDO('mysql:host=localhost;dbname=MYDATABASE', 'username', 'password');
$db->prepare('UPDATE sessionid SET options = ? WHERE retailer = ?');
$db->execute(array($options, $retailer));
You can use the WHERE clause in mysql to do this. If you are changing an existing row, you actually want UPDATE, not INSERT.
UPDATE sessionid SET options=$options where retailer = $retailer