update an array into mysql table - php

I need to update an array into mysql table.
this is my array
[cat2] => Array
(
[0] => 34
[1] => 48
[2] => 49
[3] => 46
)
and I want my output as 34,48,49,46 to move into a table called shops and column called category. This is code I written, $shop['cat2'] contains the array i posted above. Please help me. This code is keep only 34 in all fields of column category
foreach ($shop['cat2'] as $k => $v) {
$query = "UPDATE shops SET categories2=$v";
mysql_query($query);
}

In order to apply each of these array elements to one row of your category column, you will need to first fetch the a unique id from the shops table, and loop over it, using that unique identifier value in the update query's WHERE clause:
We'll call mysql_fetch_assoc() inside the foreach() loop to pull one row per one array element. This assumes you have a column shops.id which is the unique identifier per shop.
// If `id` is not the unique id per shop, substitute the correct column
$rowids = mysql_query("SELECT id FROM shops ORDER BY id");
if ($rowids) {
// Loop over your array, and do one update per array elem
foreach ($cat2 as $cat) {
$row = mysql_fetch_assoc($rowids);
$id = row['id'];
// Your values are ints, so no need to quote and escape.
// If you do use other string values, be sure to mysql_real_escape_string() them and single-quote
$upd = mysql_query("UPDATE shops SET category = $cat WHERE id = $id");
// Report error on this iteration
if (!$upd) {
echo "error updating $id" . mysql_error();
}
}
}
else {
echo "Couldn't get row ids. " . mysql_error();
}

Look into the implode function: implode(",", $shop['cat2'])
You might also want to look into Foreign Keys. When using a foreign key you can use a join SQL statement to retrieve data from multiple columns. When storing the categories as one field, like in your example, this is not possible.
You would need a new table for that: ShopCategory with columns: ShopID and CategoryID, these columns would have a foreign key relation to your Shop and Category tables respectively.
As Michael Berkowski already pointed out in the comments, if you do not use a where clause, this SQL statement will update the Category for ALL your shops!
$query = "UPDATE shops SET categories2='".implode(",", $shop['cat2'])."' WHERE id=".$shop;

Related

How to Fetch Data from MySQL Database to an Array with One Field as Index of Array

I have a table named as demo with fields id, department, createddate and status.
Now i want to fetch all the data from this table to an array with index of array as department and values from each row with same department in that array for example:
Array[department]((Array[0]=>id
createddate
status)
(Array[1]=>id
createddate
status))
Can any one help me please?
You can use the following approach if you can afford to perform a loop on fetched rows and create a new array to meet your required index structure
Once you fetch the db results, perform a loop on the results and push rows into a new array with index as department (I'm assuming its a unique property, and you should even think about renaming it to department_id).
So you easily can do something like this:
<?php
$result = mysql_query('SELECT id, department, createddate, status FROM demo');
$new_array = array();
while($row = mysql_fetch_assoc($result)) {
$department = $row['department'];
// To add enter result row including deparment
$new_array[$department] = $row;
// OR to have only id, createdate, status
$new_array[$department] =
array('id' => $row['id'],
'createdate' => $row['createdate'],
'status' => $row['status']);
}
Note: To have department (department_id) as the index, it must be a unique property.

Returning an array from a MySQL query with a JOIN operator

I have two tables;
Books
,book_id
,mbook_id (Relation with mbook_id in the master_books table)
,org_id
,book_rating
master_books
,mbook_id
,book_name
,book_authors
,book_summary
,book_pub_date
,book_ISBN10
,book_ISBN13
,book_image
Now the idea is that there are a collection of books in the master_books table, but say there were 3 libraries who all had the same book. Instead of having 3 entries of the book the books table just references the master_books table id for the book information.
To start with i've set up a simple query to get all books, like so;
$result = mysqli_query($link, "SELECT books.book_id, master_books.book_name, master_books.book_image FROM books JOIN master_books ON master_books.mbook_id WHERE org_id='" . $org_id . "'");
I'm using the following to output the data;
$books = mysqli_fetch_array($result);
foreach($books as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
The result is follows;
Key=0, Value=1
Key=book_id, Value=1
Key=1, Value=Picturepedia: 15 Plants (Picturepedia)
Key=book_name, Value=Picturepedia: 15 Plants (Picturepedia)
Key=2, Value=9780751350852.jpg
Key=book_image, Value=9780751350852.jpg
I'm trying to figure out why it duplicates with Key=0 and then Key=book_id and so on. The lines beginning with Key=0, Key=1, Key=2 shouldn't be there
if you just want to get the array with the key names and not the numeric elements use this instead:
$books = mysqli_fetch_array($result, MYSQLI_ASSOC);
It's because mysqli_fetch_array receives 2 parameters and you are ignoring the second: resulttype
As of the documentation, you have 3 options:
MYSQLI_ASSOC - you receive the field names on the array key
MYSQLI_NUM - you receive a counter on the array key
MYSQLI_BOTH - you receive both the options, all duplicated. This is the default.
As you said that
The lines beginning with Key=0, Key=1, Key=2 shouldn't be there
I think you want to call it like this: $books = mysqli_fetch_array($result, MYSQLI_ASSOC);
The response is perfectly valid.
The returned array from mysqli_fetch_array() that you store in $books represents only one line from your result table.
You can access the columns of your result table either by using the column name, e.g. book_id, or by using the position in your SELECT statement: book_id is the first field you requested, thus index 0, book_name is the second, thus index 1 and so forth.
If you don't want or need the entries with indices, use mysqli_fetch_assoc() instead.
In order to access the next lines, you have to use a loop:
while($books = mysqli_fetch_array($result)) {
// do stuff
}
This will fetch another row as long as another row is available. Once you fetched all of them, mysqli_fetch_array() will return NULL, which evaluates to false and the loop will end.

Query for certain rows and order those by date

I have an array of ids that are unique in the context of the table for each row. What I would like to do is to query the database and obtain ordered by date of insertion (it is already a field in the table) but only those tables which id is in the array
$query = SELECT this,andthis,andthis,andthis FROM table WHERE id=(inside array of ids)? ORDER BY date_of_insertion;
The result is to be fetch_assoc() and therefore obtaining a associative array. What I would really want would be something like this in the final array:
[1] id, this, andthis,andthis,andthis
[2] id, this, andthis,andthis,andthis
[3] ...
even if the table has other ids and rows that just weren't queried because they weren't in the specified array. Those that were queried should be ordered by time. Any ideas on how to achieve the best performance on this?
You can try this one:
// this is the array of ids
$array_of_ids = array();
// joins the ids in the array into a string, separating each id with a comma
$ids = implode(',', $array_of_ids);
$query = "SELECT this, andthis, andthis, andthis FROM table WHERE id IN (" . $ids . ") ORDER BY date_of_insertion";

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Add data to existing data in MySQL Database

I have a table called tblActivities. There are two fields ID and Attendees.
ID Attendees
1 Jon Jhonson
2 Ive Iveson
Which PHP function or MySQL statement do I need to use to get to this result:
ID Attendees
1 Jon Jhonson, Ive Iveson, Adam Adamer
2 Ive Iveson
In other words, how can I add new data to existing data in my database?
You need something like:
UPDATE tblActivities
SET Attendees = CONCAT(Attendees, "Ive Iveson, Adam Adamer")
WHERE id = 1;
But maybe you should change the database layout. It is preferable to have only one value in one field. You could find more information under http://en.wikipedia.org/wiki/Database_normalization.
use mysql's update statement. If you want to exeute through php then
first get the existing value using select statement,
SELECT Attendees from <table-name> WHERE ID = 1
you will get attendees existing value, put it in a php variable, now concatenate your value..
and then update,
UPDATE <table_name>
SET Attendees=<new-value>
WHERE ID=1
you would have to use the php's mysql functions to run the above queries
I think you're better off restructuring. Make a table:
ID (primary key)
ACTIVITY_ID (foreign key to activity table)
ATTENDEE (foreign key to USERS table)
Then select everything from that event and concat in PHP.
$q = mysql_query( 'SELECT ATTENDEE FROM tblActivities '.
'WHERE ACTIVITY_ID = $activity_id' );
$attendees = array();
while( $row = mysql_fetch_assoc( $q ) )
{
$attendees[] = $row['attendee'];
}
$attendees =implode( ' ', $attendees );

Categories