Insert data into a column if no data in column - php

How do I insert data into a column if that column has no values? This piece of code will not insert any values, unless I take out the if statement. Of course that isn't what I want, since that means each time the code is run, more data will be inserted into the column 'datagroup'.
include('dg_config.php');
# select column datagroup from table data
$stmt = $db -> prepare("SELECT datagroup FROM data");
$stmt->execute();
# fetch rows from data
while($row = $stmt->fetch()){
if (empty($row['datagroup'])){
$insertdg = "INSERT INTO data (datagroup)
VALUES ('Data Definitions'),('Policies'),('Systems and Process Documents'),('Purchase Orders'),('Invoices')";
$db ->exec($insertdg);
}
}
P.S dg_config.php contains the variable $db which is used for MySQL connection. Also, I have no values in the column so UPDATE won't work.
Desired output:

If you want to check if there are no records first and only insert the values then, a quick way from where you are is to say if the fetch() fails to retrieve a row then do the insert...
include('dg_config.php');
# select column datagroup from table data
$stmt = $db -> prepare("SELECT datagroup FROM data");
$stmt->execute();
if ( !$stmt->fetch() ){
$insertdg = "INSERT INTO data (datagroup)
VALUES ('Data Definitions'),('Policies'),('Systems and Process Documents'),('Purchase Orders'),('Invoices')";
$db ->exec($insertdg);
}
// re fetch the data
$stmt->execute();
This removes the while() loop altogether.

Related

PHP - INSERT and save LAST_INSERT_ID() into a variable

I'm sorry about my PHP skills, but I'm just not figuring out how to do this simple task which is INSERT a new row and save its ID into a variable.
Here's what I got:
// mysql inserting a new row
$sql = "INSERT INTO `order` (orderTitle, orderDescription, orderPrice,userID, categoryID)
VALUES('$title', '$description','$price','$userID','$category');";
$sql .= "SELECT LAST_INSERT_ID();";
$result = mysqli_multi_query($con,$sql);
$result_get_id= mysqli_next_result($con);
$row = mysqli_fetch_row($result_get_id);
$order_id = $row[0]; // <-- how to get this value??
I realized row[0] doesn't work, which is why I would like to know how to extract the LAST_INSERT_ID() value correctly.
A couple of things here...
Don't use mysqli_multi_query - it's unnecessary in your example. Use mysqli_query on the INSERT only. No need to query last insert id in SQL.
To get the last insert id, call mysqli_insert_id directly after your INSERT query. You can assign this to a variable, such as $order_id = mysqli_insert_id();
The database class you're using has built in functions for this e.g. mysqli_insert_id(), or for PDO $db->lastInsertId().
$mysqli->query("INSERT INTO order ... ");
printf ("Primary key of new record: %d.\n", $mysqli->insert_id);
http://php.net/manual/en/mysqli.insert-id.php

How to update MySQL table by calculated form value?

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();

Retrieving Last Inserted ROWID In PHP/OCI

Is it possible to retrieve the rowid of the last inserted Oracle row in PHP? I was trying:
$statement = oci_parse($conn, "INSERT INTO myTable (...) VALUES ( ...)");
$results = oci_execute($statement);
while($row = oci_fetch_assoc($statement)) {
$rowid = $row['ROWID'];
}
With no luck. I'm getting the error define not done before fetch or execute and fetch at the fetch line.
Declare:
$var = "AAAV1vAAGAAIb4CAAC";
Use:
INSERT INTO myTable (...) VALUES ( ...)
RETURNING RowId INTO :p_val
Bind your variable to a PHP variable:
oci_bind_by_name($statement, ":p_val", $val, 18);
As the previous answer was not really clear to me because it lacks some important information I will point out a similar approach.
In your SQL statement, add the RETURNING INTOclause.
$statement = oci_parse($conn, "INSERT INTO myTable (...) VALUES ( ...) RETURNING ID INTO :id");
Here ID is the name of the column you want to return. Before executing the $statement, you need to bind a PHP variable to your return value. Here I used $returnId (you don't need to declare it beforehand or assign any default value).
oci_bind_by_name($statement, ":id", $returnId);
Only after binding the variable, the statement can be executed.
$success = #oci_execute($statement);
$returnId now has the value of the ID column inserted previously.

How do I count rows in a table according to ID column (prepared statements)?

I have an array populated with records from one table and want to count corresponding records from another table and insert that into the array.
When I try this code I keep getting this error
Warning: mysqli::prepare() [mysqli.prepare]: All data must be fetched before a new statement prepare takes place
foreach ($persons as $i=>$person)
{
$stmt = $mysqli->prepare("SELECT COUNT(*) FROM order WHERE personId = ?");
$stmt->bind_param("i", $person['personId']);
$stmt->execute();
$stmt->bind_result($totalOrders);
$stmt->fetch();
$stmt->close;
$persons[$i]['totalOrders'] = $totalOrders;
}
It's as though the $stmt->close; is being ignored.
You need to add parentheses to call the close method:
$stmt->close();

Grab the last insert id from one table to put into another table

probably a simple one for you developers out there
I have this code to insert an order_id and order_name into the 'orders' table:
<?php
// start the session handler
require_once('dbfunction.php');
//connect to database
$conn = DB();
require_once('header.php');
//should we process the order?
if (isset($_POST['process'])) {
$order_name = $_POST['order_name'];
//create initial order
$stmt = $conn2->prepare("INSERT INTO orders (order_name) VALUES (?)");
//bind the parameters
$stmt->bind_param('s', $order_name);
// Execute query
$stmt->execute();
I now want to insert the order items into the order_items table and I cant seem to keep that same ID that was created when inserting into the 'orders' table and add it to the 'order_items' table along with the order_items. Here is my code:
//this gets the most recent auto incremented ID from the database - this is the order_id we have just created
$order_id = mysql_insert_id();
//loop over all of our order items and add to the database
foreach ($_SESSION['order'] as $item) {
$prod_id = $item['prod_id'];
$quantity = $item['quantity'];
$prod_type = $item['prod_type'];
$stmt = $conn2->prepare("INSERT INTO order_items (order_id, prod_id, quantity, prod_type) VALUES (?, ?, ?, ?)");
//bind the parameters
$stmt->bind_param('iiis', $order_id, $prod_id, $quantity, $prod_type);
// Execute query
$stmt->execute();
}
echo "<p class='black'>Order Processed</p>";
I would guess it's because whatever database library you are using is doing something to invalidate the mysql_insert_id (assuming it's even using the mysql functions). I'd suggest you look into the library to find out what method they suggest you use instead.
SQL Server has ##IDENTITY
It looks like mySQL has LAST_INSERT_ID();
My guess is you are using mySQL. If not, then please let me know the version so I can update

Categories