Looping array to update mysql table - php

Is it possible to construct a loop which takes every single value from an array and then updates a mysql table?
What the array looks like
output
Team Blue
4
4
Team Red
4
4
Bare in mind that the 4's are Id's.
Array code
$players = $lista;
shuffle($players);
$player_count = count($players);
$players_per_team = $player_count/2;
$teams = array_chunk($players,$players_per_team);
$team_1 = $teams[0]; // Lag 1
$team_2 = $teams[1]; // Lag 2
echo "Team Blue";
echo "<br>";
foreach ($team_1 as $value) {
echo $value . "<br>";
}
echo "<br>";
echo "Team Red";
echo "<br>";
foreach ($team_2 as $value) {
echo $value . "<br>";
}
How can i select each element in the array?
Basically all i need to do is to update a single column for each id in both arrays.
See picture
https://gyazo.com/ceb49db66ba85b9a6adfa0daf30c7a57
I want to update "team" column.
My guess is that i need to make some sort of loop, but i have no clue on how to select each element and then querying it.
So my question is.
How can i select each element in the array and loop some sort of query to update a single column?
If i need to provide more information, just tell me!
Thank you for taking your time reading my question, kind regards Jonas

Google is your friend:
"php mysqli update column"
Best Result: https://www.w3schools.com/php/php_mysql_update.asp
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Before you update or insert data check if your value are a integer
if (is_numeric($myArr[0])) {
// number
} else {
// something other
}

Related

Reading SELECT LAST_INSERT_ID(), which seems to produce an array

I am populating a MySQL database using PHP and SQL languages. The table I am populating is called project. After I add the record to project, I would like to send out an email including the project_id and project_title. I thus need to know the project_id after I populate the project table.
The command: $sql = "SELECT LAST_INSERT_ID()"; is returning an array. I have tried several guesses of what is in the array, without any luck.
public function add_project($project_title, $project_description,
$skill_cat_id, $name_id) {
$dbConn = new DatabaseConn();
$this->name_id = $name_id;
$this->skill_cat_id = $skill_cat_id;
if($this->check_for_duplicates() != null) {
$message = "This Project already exist!";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$sql = "INSERT INTO project "
. "(project_id, project_title, project_start_date, "
. "project_description, skill_cat_id, volunteer_id, response_id, name_id) "
. "VALUES (DEFAULT, $project_title, DEFAULT, "
. "$project_description, $skill_cat_id, DEFAULT, DEFAULT, $name_id)";
try {
$dbConn->exec($sql);
}
catch(PDOException $e) {
$message = $sql . "<br />" . $e->getMessage();
echo "<script type='text/javascript'>alert('$message');</script>";
}
$dbConn2 = new DatabaseConn();
$sql = "SELECT LAST_INSERT_ID()";
try {
$statement = $dbConn2->prepare($sql);
$statement->execute();
$result = $statement->fetch();
$statement->closeCursor();
}
catch(PDOException $e) {
$message = $sql . "<br />" . $e->getMessage();
echo "<script type='text/javascript'>alert('$message');</script>";
}
return $result;
}
}
I am expecting the project_id of the project table, yet the command is returning an array.
PDOStatement::fetch() always returns an array, which is one row of the result set. The array is either an ordinal array or a hash array indexed by column name.
It doesn't matter that your query is guaranteed to have one column and one row. It's still a result set, for which fetch() returns an array. The array it returns will have one entry, corresponding to the single column of your query.
If you want to return just one column as a scalar, try PDOStatement::fetchColumn().
See the documentation for description and a code example.
You can get last insert Id from the pdo object itself. https://www.php.net/manual/en/pdo.lastinsertid.php

Why does echo $row[1] work but not echo $row[2]?

I have a MySQL database and am trying to print out the contents of specific rows. For some reason echo $row[1]; prints out the contents of row 1 perfectly, but I'm unable to do the same for the other rows (echo $row[2];, echo $row[3];, etc). The table has a unique index column with four rows labeled 1-4.
What I'd eventually like to do is print out just the contents of the last row, which I thought would look something like echo $row['$maxrows']; however I can't even get the syntax for printing any row past 1!
I think that this may be an issue with my table, but can't quite see what it is as there is an index column. Any suggestions or pointers would be appreciated?
What might I do to echo rows in my table past row 1?
UPDATE
var_dump($row); returns the below
{ [0]=> string(1) "1" ["Index"]=> string(1) "1" [1]=> string(121) "https://www.tilley.com/media/catalog/product/cache/image/1100x1100/e9c3970ab036de70892d86c6d221abfe/t/t/ttw2_black2_a.jpg" ["Sketch"]=> string(121) "https://www.tilley.com/media/catalog/product/cache/image/1100x1100/e9c3970ab036de70892d86c6d221abfe/t/t/ttw2_black2_a.jpg" }
The table has two columns:
1-Name: Index - int(11) - AUTO_INCREMENT
2-Name: Sketch - text
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Table";
$result = mysqli_query($conn, $sql);
$maxrows = mysqli_num_rows($result);
//$result = $conn->query("SELECT * FROM Table");
$row = $result->fetch_array(MYSQL_BOTH);
echo $maxrows;
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
//echo $result;
$conn->close();
Your result array has 4 keys: 0, Index, 1 and Sketch, that's the results of the first row only. You're querying 2 columns but try to access 4 columns. Column numbering starts with 0. And you're not iterating the result rows. That $row = $result->fetch_array(MYSQL_BOTH); should be in a loop.
Turn on error reporting. PHP would show you which undefined variables your accessing.
Use PDO in favor to mysqli.
Don't create an array with both column name indexes and numeric indexes (don't use MYSQL_BOTH). Use PDO::FETCH_ASSOC or PDO::FETCH_NUM.
Start using var_dump() instead of echo for debugging. Always.
Use a foreach loop when processing the result array.

How to select data from an entire column and present it as separate choices in a select tag.

I think this question is going to be rather interesting. So, as the title suggests, I am trying to make a dynamic select field. Basically, when the time comes my web app will connect to my database, and pull the entire row that matches my query. My question is this: How can I present the data from ONE of the columns within the row as INDIVIDUAL options within the select tag? This is what I am trying right now:
<select>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "people";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$search_query = "SELECT * FROM people_list WHERE person_id = $_SESSION[person_id]";
$result = $conn->query($search_query);
while($person_result_list = mysqli_fetch_assoc($result)){
echo "
<option value='$result[person_result_list]'>'$result[person_name]', '$result[person_result_list]'</option>
";
}
}
?>
</select>
This is returning an error:
Cannot use object of type mysqli_result as array
Which should be pretty straight forward to fix, but I just can't figure out the workaround to this. Any ideas?
Thanks all!
Cannot use object of type mysqli_result as array
That's because of this statement,
<option value='$result[person_result_list]'>'$result[person_name]', '$result[person_result_list]'</option>
^^^^^^^ ^^^^^^^ ^^^^^^^
$result is a MySQLi result object, not an array.
My question is this: How can I present the data from ONE of the columns within the row as INDIVIDUAL options within the select tag?
Simply fetch the row the result set and use foreach loop to display each individual column value inside <option> element, like this:
// your code
$search_query = "SELECT * FROM people_list WHERE person_id = $_SESSION[person_id]";
$result = $conn->query($search_query);
$person_result_list = mysqli_fetch_assoc($result)
foreach($person_result_list as $value){
echo '<option value="' . $value . '">' . $value . '</option>'
}
// your code
you can use GROUP_CONCAT in the query. It will return you a comma separated string of the values of your target column only. You then can split this string to make it an array to use for the select dropdown.

Populating array in PHP from MySQL table

I am newbie to PHP and need to seek your help on how to populate the array which is $dataArray[] with the rows of MySQL so that I will be able to call the data Array in some other function or say I want to print the $dataArray as above. I would be thankful to you if you can provide me example code modifications in my below code
<?php
$dataArray=array();
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT reg_date,xyz,pqr FROM stuvw";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$test = mysqli_num_rows($result);
echo $test;
while($row = mysqli_fetch_assoc($result))
{
$populate = '"' . $row["reg_date"]. '"'."=>" . $row["xyz"]. ", " ;
$dataArray[$populate] = $test;
}
echo $dataArray[$populate];
}
mysqli_close($conn);
?>
You can use an Associative array. This stores the data in a key-value format.
$dataArray[ $row['reg_date'] ] = $row['xyz'];
What you are doing in you example is creating a string in the $populate variable and using it as a key in the $dataArray. The number of rows returned from the SQL query is then stored as the value for each item in the $dataArray. This number is in the $test variable.
The key needs to be unique however so it makes sense to use the primary key from your MYSQL result as you key (if necessary).
Have a read through W3Schools PHP course.
http://www.w3schools.com/php/php_arrays.asp

How can I pull items from database select with session array?

I have code that adds an array to a session like this:
array_push($_SESSION['cart']['1'] = 3);
array_push($_SESSION['cart']['18'] = 1);
This would add item id "1" with quantity "3" and add item id "18" with quantity "1". I want to show these items from database on cart page.
I'm not good in php or sql, but something like:
while (list ($id, $quantity) = each ($_SESSION['cart'])) {
$results = $conn->query("SELECT * FROM products ORDER BY id ASC");
}
and do something like find $id(from session) = $id(from database) so I could show session as information from database. With item name, item desc., item price, and quantity.
Here is a quick example highlighting what u're trying to retrieve (id_item) from $_SESSION :
http://www.tehplayground.com/#Iyf7c0LTM
$arr = array();
$arr['cart']['1'] = 3;
$arr['cart']['18'] = 5;
// This loop will display every id_item that had be added to the "cart"
foreach($arr['cart'] as $row)
{
print "id_item : " . $row . "\n";
}
U can use now make ur sql query :
$sql = "SELECT * FROM products WHERE id =". $row;
EDIT - Since it was unclear for you, I made u the direct answer :
<?php
session_start();
// Examples of shopped items (added to $_SESSION['cart'])
$_SESSION['cart']['1'] = 3;
$_SESSION['cart']['18'] = 5;
// This loop will display every id_item that had be added to the "cart"
// Further informations how foreach works with array
// https://stackoverflow.com/questions/10057671/how-foreach-actually-works
foreach($_SESSION['cart'] as $row)
{
print "id_item : " . $row . "\n";
}
// Full Display to help understanding the process
print "<pre>";
print_r($_SESSION['cart']);
print "</pre>";
?>
Advanced explanations about "how foreach interacts with array" : here
EDIT 2 :
Fill db variables + column names of your table
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$mysqli = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Query the DB - Get itemID & quantity added in the cart table
$query = "SELECT itemID, itemQuantity FROM cart";
$result = $mysqli->query($query);
// Return the result into an array
$res_array = $result->fetch_array();
// Add the items into $_SESSION
// Pattern : $_SESSION['cart']['$itemId'] = $itemQuantity
foreach($res_array as $row)
$_SESSION['cart'][($row['itemID'])] = $row['itemQuantity']
print "<pre>";
print_r($_SESSION['cart']);
print "</pre>";
?>
Example : here
Rather than getting everything from the database and then comparing in php you can do something like this to only get the records that you need:
"SELECT * FROM products WHERE id IN(1,18) ORDER BY id ASC"
The PHP might be as simple as: $in = implode(",", $_SESSION['cart']); although you should also make sure to protect against SQL injection.

Categories