save pdo execution results into an array? - php

I am using the following to update a table in my db with various values (I have shortened this example to two). Given an array of users ($user_set) I check to see if settings for the user exist... if they do I update the users row... if they do not then I create a row for the user.
The code below works fine, however, I need to return an array of the rows I just changed so I can update the page display with js.
Essentially what I want to do is $result_array[] = $stmt->execute($binding); (all values of the row updated/inserted)
This way I could echo json_encode($result_array); and have an array of all rows I just updated/inserted for use with js.
Is something like this possible or will I need to create the array on my own in php to return?
<?php
//set bindings
$binding = array(
'one' => $settings['one'],
'two' => $settings['two'],
'user_id' => $user['user_id']
);
foreach($user_set as $key)
{
// check if program settings exist or not
$stmt = $db->prepare("SELECT * FROM settings WHERE user_id = ?");
$stmt->execute(array($key['user_id']));
// program_settings result is
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// if result then settings exist and update... if not insert one
if($result)
{
//prepare update statement
$stmt = $db->prepare("UPDATE settings SET one = :one, two = :two WHERE user_id = :user_id");
}
else
{
//prepare insert statement
$stmt = $db->prepare("INSERT INTO settings (user_id, one, two) VALUES (:user_id, :one, :two)");
}
//set comp id
$binding['user_id'] = $key['user_id'];
// execute the update
$stmt->execute($binding);
}
?>

After you use a stmt->execute(); to execute some sql, you can use stmt->fetchAll(); to take all of the rows that has been affected by your sql statement.

Related

How to match auto increment from table 1 into table 2 in POST method PHP [duplicate]

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.

Pass an SQL query to php PDO function and execute [duplicate]

Currently Im trying to create a PDO class where I will have a method to run a query like INSERT, UPDATE, or DELETE.
For examaple this is my method for a SELECT
public function getPreparedQuery($sql){
$stmt = $this->dbc->prepare($sql);
$stmt->execute([5]);
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(!$arr) exit('No rows');
$stmt = null;
return $arr;
}
And i Simply call it like this:
$stmt = $database->getPreparedQuery($sql2);
var_export($stmt);
And so far I know that a runQuery should work something similar to this:
Insert Example without using a method:
$idRol = "6";
$nomRol = "test6";
$stmt = $database->dbc->prepare("insert into roles (idRol, NomRol) values (?, ?)");
$stmt->execute(array($idRol,$nomRol));
$stmt = null;
But I want to make it into an universal method where i simply can pass the sql sentence, something like this:
$database->runQuery($query);
but the query can happen to be
$query = "INSERT INTO roles (idRol, NomRol) VALUES ('4','test')";
or
$query = "INSERT INTO movies (movName, movLength, movArg) VALUES ('name1','15','movie about...')";
So how do I slice the arg $query so I can get all the variables that are being used in order to make an universal runQuery?
Because I can imagine that my method should be something like this
runQuery([$var1 , $var2, $var3....(there can be more)] , [$var1value, $var2value, $var3value...(there can be more)]){
$stmt = $database->dbc->prepare("insert into movies($var1 , $var2, $var3....(there can be more)) values (?, ? , ? (those are the values and there ca be more than 3)"); //how do i get those "?" value and amount of them, and the name of the table fields [movName, movLength, movArg can be variable depending of the sentence]?
$stmt->execute(array($var1,$var2, $var3, ...)); //this is wrong , i dont know how to execute it
$stmt = null;
}
You need to add a second parameter to your function. Simply an array where all those variables would go. An array by definition can have an arbitrary number of elements, which solves your problem exactly:
public function runQuery($sql, $parameters = []) {
$stmt = $this->dbc->prepare($sql);
$stmt->execute($parameters);
return $stmt;
}
this simple function will run ANY query. You can see the usage example in my article dedicated to PDO helper functions:
// getting the number of rows in the table
$count = $db->runQuery("SELECT count(*) FROM users")->fetchColumn();
// the user data based on email
$user = $db->runQuery("SELECT * FROM users WHERE email=?", [$email])->fetch();
// getting many rows from the table
$data = $db->runQuery("SELECT * FROM users WHERE salary > ?", [$salary])->fetchAll();
// getting the number of affected rows from DELETE/UPDATE/INSERT
$deleted = $db->runQuery("DELETE FROM users WHERE id=?", [$id])->rowCount();
// insert
$db->runQuery("INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);
// named placeholders are also welcome though I find them a bit too verbose
$db->runQuery("UPDATE users SET name=:name WHERE id=:id", ['id'=>$id, 'name'=>$name]);
// using a sophisticated fetch mode, indexing the returned array by id
$indexed = $db->runQuery("SELECT id, name FROM users")->fetchAll(PDO::FETCH_KEY_PAIR);
As you can see, now your function can be used with any query with any number of parameters

SQL UPDATE Statement does not affect any rows (PHP)

I'am currently working on a project and want to make a simple page where I can edit groups. I had everything working fine in XAMPP and tried uploading it to the server, but it won't affect any rows in the database.This is the statement:
UPDATE user_groups
SET name = 'TEST',
name_short = 'test',
color = 'green',
category = 'MMORPG'
WHERE id = 2
and:
Affected rows (UPDATE): 0
Is the answer. Creating new groups works fine (Local creating and editing works and I did not change anything in the statements since I uploaded both)
This is what the row looks like that I am trying to affect
EDIT:
$sql_update_info = "UPDATE user_groups SET name = '$new_title', name_short = '$new_short', color = '$new_color', category = '$new_cat' WHERE id = $group_id";
$query_update_info = mysqli_query($mysqli, $sql_update_info);
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($mysqli));
echo '<br><span style="color:white;">'.$sql_update_info.'</span>';
Is what the PHP part looks like when clicked on the button.
1st : Try to use prepared statement to avoid sql injection.
2nd : Execute() will return true or false so based on that you need to handle the error like below.
$stmt = $mysqli->prepare("UPDATE user_groups SET name = ?, name_short = ?, color = ?, category = ? WHERE id = ?");
$stmt->bind_param('ssssi', $new_title, $new_short, $new_color, $new_cat, $group_id);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
$r = $stmt->execute();
if(!$r){
echo $stmt->error;
}else{
$row_count= $stmt->affected_rows;
}
$stmt->close();
$mysqli->close();

Returned results from JSON to insert into mysql table and then email the results

I need help with how to insert the returned results of a JSON array into an sql table and then email the results returned.
Below is my php script so far that successfully gets the results of a query into a JSON array
<?php
// set up the connection variables
$db_name = 'dbanme';
$hostname = 'host';
$username = 'username';
$password = 'password';
// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
// a query get all the records from the users table
$sql = 'SELECT tabel1.id,table1.type FROM table1 LEFT JOIN table2 ON table1.id=table2.id WHERE table1.id NOT IN ( SELECT table2.id FROM table2)';
// use prepared statements, even if not strictly required is good practice
$stmt = $dbh->prepare( $sql );
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
// count number of results returned in the array
$countresults = count($result);
echo $countresults;
if ( $countresults > 0 ) {
// convert to json
$json = json_encode( $result );
// decode the results returned and insert them into table 2
// email the results returned
}
else {
echo ' no results found';
}
?>
UPDATE :
Table 1 structure :
ID INT 10
Type VARCHAR 50
Table 2 structure :
ID INT 10
Type VARCHAR 50
I realised I dont need to encode result into JSON but I still cant get the code to get the results returned from an array and insert them into tabl2 and then email the results straight after.
First you have to tell us why you converted the results to json in the first place. You already have an array, you don't need a JSON string in your case.
Anyhow, you convert a JSON string back to an array like this:
$yourArray = json_decode($json)
Now you say you want to insert the data into table two. I don't know how your table looks like, but if I look at your code, I guess your sql would look something like this:
$sql = 'INSERT INTO table2(id, type) VALUES (:id, :type)';
So your code would look something like this:
$sql = 'INSERT INTO table2(id, type) VALUES (:id, :type)';
$stmt->bindParam(':id', $yourArray ['id']);
$stmt->bindParam(':type', $yourArray['type']);
$stmt = $dbh->prepare( $sql );
$stmt->execute();
If you want to send the results via mail, you just use the default mail function:
$to = 'RECIEVER#MAIL'
$subject = 'SUBJECT';
$message='Your values are: '.$yourArray ['id'].' - '.$yourArray['type'];
mail($to,$subject,$message);
If the default mail function doesn't work, your server may not allow it (sometimes for security reasons). In this case I recommend using a third party library like PHPMailer
Your question did not reveal many informations, I did the best I could but the code above is still more of a pseudocode.

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.

Categories