Using foreach loop to update MySQL table with array of IDs - php

I'm trying to update a MySQL table with three columns (id, franchise_id, state_id) with data from an array by using a foreach loop. The table updates but the four rows that match the franchise_id are being updated with the last item in the array (4). I can't figure out where the error is.
Data passed to the function:
$states = [1,2,3,4];
$franchise_id = 5;
The update function:
public static function update($franchise_id, $states)
{
try
{
// establish db connection
$db = static::getDB();
$sql = "UPDATE franchise_states SET state_id = ? WHERE franchise_id = ?";
$stmt = $db->prepare($sql);
foreach($states as $state)
{
$stmt->execute([$state, $franchise_id]);
}
return $stmt;
}
catch (PDOException $e)
{
echo "Error updating franchise data: " . $e->getMessage();
exit();
}
}
I appreciate any help.
Thanks!

Actually it's updating for all the values in $states array but the last one stays because, well, it is the last executed one.
You try to update state_id against the same value franchise_id=5 and since all of them has the same franchise id, the last value stays.

Have you try to edit this line?
foreach($states as $state)
to
foreach($state as $states)

Related

Pushing values and keys to an multidimensional array from the database inside a foreach loop without repetitions

I'm trying to combine two tables from a database, and based on my first one, I want to retrieve some value from the other one, and add them to an array.
Here's my problem:
My first database looks like that:
FIRST TABLE:
id, credit_type, association_name, address, city, province, postal_code, country, cycle_type, cycle_begin, cycle_months
My second database instead looks like that:
SECOND TABLE:
id, association_id, designation_name
The id in my first table matches the association_id in my second table so I don't need an INNER JOIN.
My approach is the following:
<?php
public function my_function()
{
$sql = ee()->db->select('*')->from('first_table')->get();
$data['database'] = [];
if ($sql->num_rows() > 0)
{
foreach($sql->result_array() as $row)
{
$id[] = $row['id'];
$data['database'][] = $row;
}
}
foreach ($data['database'] as $key => $value) {
$association_query = ee()->db->query("SELECT * FROM second_table WHERE id = $id");
foreach($association_query->result_array() as $row_two)
{
if ($association_query->num_rows() > 0)
{
$data['database'][$key]['associations'][] = $row_two['designation_name'];
}
}
}
return ee()->load->view('index', $data, true);
}
?>
The sintax ee()->db->select('*') is a prepared statment from expression engine and it's equal to SELECT * FROM first_table (sanitaized).
So as you can see, I try to pass the value $id, which is an array, to my query. The thing is that as soon as I push the value like that $id[] = $row['id'] I create a nice array, but when I loop through my foreach loop, it multiplies my array in many other arrays so I'm not able to run my query, even if I'm technically in a foreach loop.
Plus, as soon as I try to push the result of my query in my array, let's say changing the id in a static id for instance id=3, I obtain a really weird result, like so many arrays repeated with 1 value, 2 value, 3 value and so on, when I'd like to push my key 'association' only where it is presented in the other table.
If you won't do it on SQL, at least don't execute the second query so many times.
<?php
public function my_function()
{
$assocs = array();
$data = array('database' => array());
$association_query = ee()->db->query("SELECT * FROM second_table");
if ($association_query->num_rows() > 0) {
foreach($association_query->result_array() as $row) {
$assocs[$row['association_id'][] = $row['designation_name'];
}
}
$sql = ee()->db->select('*')->from('first_table')->get();
if ($sql->num_rows() > 0) {
foreach($sql->result_array() as $row) {
$id_check = $row['id'];
if (isset($assocs[$id_check])) {
$row ['associations'] = $assocs[$id_check] ;
}
$data['database'][] = $row;
}
}
return ee()->load->view('index', $data, true);
}
?>
Regards

How to echo specific column names using "SELECT *" query, get_result() - MySQLi

I have the following code:
public static function selectBy(Database $database, $columnName, $value){
$connection = $database->getConnection();
$stmt = $connection->prepare('
SELECT * FROM `Logs`
WHERE ' . $columnName . ' = ?;');
$stmt->bind_param('s', $value);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
$finalResult[] = $row;
}
return $finalResult;
And it's implementation:
$logsArray = Log::selectBy($this->database, "ID", "423");
foreach($logsArray as $key=>$logArray){
foreach($logArray as $anotherKey=>$log){
echo $log . "<br />";
}
}
I am trying to find a way to target only specific row fields that we're returned from the database, for example, echo only the IP of the first log that was returned.
another example is to assign all the fields that we're return to a Log object, one field to a variable at a time, or all at once.
The result will be a row of objects, of type "Log" that reflect what's in the database.
One more problem I have encountered is that I have an extra field in each row of the two dimensional array returned by fetch_assoc(), which is called "array + an incrementing number", for example:
Array 0
Array 1
Array 2
Clearly it's the array number inside the first array, using foreach it goes over it by default.
Any way to ignore it using foreach? Or remove / avoid inserting them in the first place?
Thanks in advance.

displaying results from mysql with php foreach.... very confused

Hi I'm getting confused as to how to display results with foreach loops. It seems there are slight differences depending on the structure of the array? ie if its a simple array, associative or multi-dimensional? I have looked at other answers for this site but I am still very much confused.
i have connected to mysql db with this code
try
{
$pdo = new PDO('mysql:host=localhost;dbname=****', '*****',
'*****');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.' . $e->getMessage;
echo $error;
exit();
}
//next i want to retrieve the 'id' and 'name' from a db table...
$results = $pdo->query('select id, name FROM author');
//now I want to display those results on the page... i tried a foreach loop...
foreach ($results as $result) {
echo $result;
}
//but this just displays error message...
Parse error: syntax error, unexpected '$results' (T_VARIABLE), expecting '(' in C:\xampp\htdocs\Connect\admin\authors\test.php on line 6
Please help as im very confused. I just want to know how to display results from a db query like this with a foreach, and what rules apply when displaying different kinds of results from such queries.
I think it involves writing a foreach something like this ....
foreach ($results as $result=> $item) {
echo $item;
}
but i dont undertsand this either.
Any simplified approach to this would be greatly appreciated as I have been stuck on this for some time.
Thanks Rob.
$result is an array not the string.
$stmt = $pdo->prepare("SELECT id, name FROM author");
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $result) {
echo $result['id'];
echo $result['name'];
}
or print the array like this,
foreach ($results as $result) {
print_r($result);
}
You could try it with prepared statements, I always do even if I am not injecting parameters, keeps things a bit clearer.
$stmt = $pdo->prepare('select id, name FROM author');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
You can use the statement fetch method, and with the constant PDO::FETCH_ASSOC to ensure each row is an associative array.
If you're just looking to SELECT something from a database, below is the general format of what you'll need:
try {
//First, you initialise a connection to the database (in this case I'm using *constants*).
$dbh = new PDO('mysql:host=localhost; dbname='.DB_NAME, DB_USER, DB_PASS);
//Secondly, we'll prepare our query - SELECT the id and name FROM table author
$stmt = $dbh->prepare("SELECT id, name FROM author");
// Then we must execute the query
$stmt->execute();
// After execution, we must perform some function to get the results
// This function fetches ALL the results as an array so we can loop
// through them with foreach.
// (Other methods include a while loop and "fetch()" for one row at a time)
$results = $stmt->fetchAll();
// Then we just loop through everything
foreach ($results as $row) {
echo $row['id'];
echo $row['name'];
}
} catch (PDOException $e) {
echo $e->getMessage();
}

PDO prepare working when i reload the second time the page

output JSON is here .when i reload the second time it has new recodes.but when i update the first time it does not have recodes
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=$db', "user", "pass");
foreach($dbh->query('SELECT * FROM `jos_jea_towns` LIMIT 0, 500 ') as $row) {
echo '<pre>' . json_encode($row, JSON_PRETTY_PRINT).'</pre>';
}
$insertObject = $dbh->prepare("INSERT INTO `jos_jea_towns` (id, value) VALUES (:id, :value)");
$insertObject->bindParam(':id', $id);
$insertObject->bindParam(':value', $value);
// insert one row
$id = 433;
$value = 'yyy';
$insertObject->execute();
// insert another row with different values
$id = 434;
$value = 'xxx';
$insertObject->execute();
// insert another row with different values
$id = 435;
$value = 'Samitha';
$insertObject->execute();
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
How is this PDO prepare working or is there any problem with my JSON file?
Well, you are selecting first, and updating later. So the first time, you select, before you've added the records, then you add the records.
On the second reload, you've already added the records (from the previous iteration), and so the inserted records are displayed.
To solve, insert first, and select after. That way you can see the changes you've just made.

Can't print all rows and columns from table

This might be one easy question.
I have this table:
Table Image
bairro = neighborhood / preco = price
This is a reference table with prices.
I'm trying to print a table with the neighborhood and the price, but it's not happening as I'd like:
ProblematicTable
As you guys can see, each value is being printed 3 times!
The code is this:
function getInfo()
{
$this->sql = "SELECT * FROM deliverypricestable";
$this->query = $this->mysqli->query($this->sql);
while($this->result = $this->query->fetch_assoc())
{
foreach ($this->result as $key)
{
echo "<tr><td>".$this->result["bairro"]."</td>";//neighborhood
echo "<td>".$this->result["preco"]."</td></tr>";//price
}
}
I know this problem is probably related with the numbers of column on the deliverypricestable, but I'm just learning to code, and lil lost, please help me!
function getInfo()
{
$query = "SELECT * FROM deliverypricestable";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo "<tr><td>".$query->result["bairro"]."</td>";//neighborhood
echo "<td>".$query->result["preco"]."</td></tr>";//price);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
}
You might find - http://php.net/manual/en/mysqli.query.php - useful for documentation on what you are trying to do.
There's no reason to loop twice. The while loop will execute while there is a new row. This new row is stored in $this->result.
function getInfo()
{
$this->sql = "SELECT * FROM deliverypricestable";
$this->query = $this->mysqli->query($this->sql);
while($this->result = $this->query->fetch_assoc()) {
echo "<tr><td>".$this->result["bairro"]."</td>";//neighborhood
echo "<td>".$this->result["preco"]."</td></tr>";//price
}
}
What your code is doing is looping through all the rows and then for each row, you're looping through all the keys (columns) belonging to the row. You have 3 columns and so for each row, you print the values 3 times.

Categories