I am new to php and trying to do the following:
1) parse a PLS file from an external link
(which I've managed to do it using stack overflow example here: How do I parse a .pls file using PHP? Having trouble with parse_ini_file)
2) Insert the Title and File data obtained from parsed code into a database table like this:
output format from parse code:
[Title1] => testradiostn
[File1] => http://testradiostn.com/
How do i put these two in an array so that I can insert it into a table like below
--------------------------------------------------
| id | radio_stn | url |
-----|----------------|--------------------------|
| 1 | testradiostn | http://testradiostn.com/ |
| 2 | testradiostn2 | http://testradiostn2.com/|
| 3 | x | x |
| 4 | x | x |
$title = ???; //title from parsed pls file
$file = ???; //file from parsed plsm file
/*Also how do I insert more than one data at one go*/
$sql = "INSERT INTO Table_1 (radio_stn, url) VALUES (?, ?)";
$params = array($title, $file);
$stmt = sqlsrv_query( $conn, $sql, $params);
Sorry for the long post.Thanks in advance.
How do i put these two in an array so that I can insert it into a table like below
To put $title and $file into an array, you would do like:
$params = array($title, $file);
What parse_ini_file returns is an associative array. That means you should access elements by key name. To get a file and title you can var_dump the parsing result to see its structure . But probably something like this should work if I understood your question :
$title = $result['title'];
$file = $result['file'];
Related
I created the JSon file using the c# to export the selected records from the local MySQL database. The php code is used to insert the JSon file recods to the MySQL remote database. But the problem is, when I run the php code, it only inserts the first record from the JSon to the database rather than all records in the JSon file.
But I want to insert all the records to the database.
table : tbl_sales
the id field is AutoIncrement
+--------------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+-------------+------+-----+---------+----------------+
| sale_item | varchar(20) | NO | | NULL | |
| sale_qty | int(11) | NO | | NULL | |
| local_row_added_on | datetime | NO | | NULL | |
| last_edited_on | datetime | YES | | NULL | |
| id | int(11) | NO | PRI | NULL | auto_increment |
+--------------------+-------------+------+-----+---------+----------------+
<?php
$connect = mysqli_connect("localhost", "root", "", "mytest"); // 1.
$query = '';
$table_data = '';
$filename = "path.json";
$data = file_get_contents($filename); // 2.
$array = json_decode($data, true); // 3.
foreach($array as $row) // 4.
{
$query .= "INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on, last_edited_on) VALUES ('".$row["sale_item"]."', '".$row["sale_qty"]."', '".$row["local_row_added_on"]."', '".$row["last_edited_on"]."'); "; // 5.
mysqli_query($connect, $query); // 6.
}
echo "<h1>Successfully Imported JSON Data</h1>";
// 1. Connect PHP to MySQL Database
// 2. Read the JSON file in PHP
// 3. Convert JSON String into PHP Array
// 4. Extract the Array Values by using Foreach Loop
// 5. Make Multiple Insert Query
// 6. Run Mutliple Insert Query
?>
JSon file records(path.json) :
[
{
"sale_item":"Sugar",
"sale_qty":"5",
"local_row_added_on":"2018-05-08 10:10:24",
"last_edited_on":"2018-05-08 10:10:24",
"id":"1"
},
{
"sale_item":"Keyboard",
"sale_qty":"2",
"local_row_added_on":"2018-05-07 08:14:41",
"last_edited_on":"2018-05-07 06:14:53",
"id":"2"
},
{
"sale_item":"Biscuit",
"sale_qty":"3",
"local_row_added_on":"2018-05-06 12:15:17",
"last_edited_on":"2018-05-06 12:15:35",
"id":"3"
},
{
"sale_item":"Pen",
"sale_qty":"25",
"local_row_added_on":"2018-05-14 03:20:22",
"last_edited_on":"2018-05-14 03:20:25",
"id":"4"
},
{
"sale_item":"Snacks",
"sale_qty":"6",
"local_row_added_on":"2018-05-07 05:30:40",
"last_edited_on":"2018-05-16 05:30:40",
"id":"5"}
]
When building your query, you are using
$query .=
This adds the content onto the previous value. The first time this is OK as there is no previous content. Second time it adds a new insert onto the old one and will fail. Remove the . to just set a new statement.
$query =
You should also look into prepared statements and bind variables, this helps protect from SQL injection and can aid in other ways.
Please try this, Your query is :
INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on,
last_edited_on) VALUES ('Sugar', '5', '2018-05-08 10:10:24', '2018-05-08
10:10:24');
INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on,
last_edited_on) VALUES ('Keyboard', '2', '2018-05-07 08:14:41', '2018-05-07
06:14:53');
INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on,
last_edited_on) VALUES ('Biscuit', '3', '2018-05-06 12:15:17', '2018-05-06
12:15:35');
INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on,
last_edited_on) VALUES ('Pen', '25', '2018-05-14 03:20:22', '2018-05-14
03:20:25');
INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on,
last_edited_on) VALUES ('Snacks', '6', '2018-05-07 05:30:40', '2018-05-16
05:30:40');
and you should execute your query after the foreach loop:
$query='';
foreach($array as $row) // 4.
{
$query .= "INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on, last_edited_on) VALUES ('".$row["sale_item"]."', '".$row["sale_qty"]."', '".$row["local_row_added_on"]."', '".$row["last_edited_on"]."'); "; // 5.
}
$result = mysqli_multi_query($connect,$query ) or die("Unable to insert: //6".mysql_error());
I am trying to output encrypted data stored in a table in a BLOB format, but it's not working. I inserted it using prepared statements, and when I checked on the mysql command line client, it showed the entry has been recorded, but the blob fields are empty, and every other field has some value. Also, the blob field must not be null, as I have specified it while table creation, so I considered that the command line cannot show the blob field data.
So using php, I have tried to return a base64_encode value of the blob field, but it didn't help. It's still empty. What do I do?
P.S.: It's not an image, it's encrypted text with AES-256.
$stmt = $conn->prepare("INSERT INTO data_store (eid, ekey, ecipher) VALUES (?, ?, ?)");
if($stmt->bind_param("sbb", $eid, $ekey, $ecipher)) {
echo "Successful";
}
// set parameters and execute
$eid=$postedID;
$ekey=$postedKey;
$ecipher=$postedCipher;
$stmt->execute();
$stmt->close();
$conn->close();
After that I tried to return the BLOB value encoding it, but it returns nothing whereas the value of id which is a string does show up. How do I solve this? I need to encrypt the data and later decrypt it plaintext for the website.
How do I achieve this?
Thanks a lot.
P.S.: I haven't tried decrypting yet, I need the encrypted value first, so suggesting to decrypt it first won't be a very helpful one.
The table looks like this-
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| eid | varchar(255) | NO | PRI | NULL | |
| ekey | blob | NO | | NULL | |
| ecipher | blob | NO | | NULL | |
+-------------+---------------------+------+-----+---------+----------------+
The problem was solved when I changed the parameters to string "s", this seems to work correctly since the variables I held the data into were strings, so it fits in.
So the corrected code is:
$stmt = $conn->prepare("INSERT INTO data_store (eid, ekey, ecipher) VALUES (?, ?, ?)");
if($stmt->bind_param("sss", $eid, $ekey, $ecipher)) {
echo "Successful";
I am not saying this is a perfect solution, but it seems to solve my problem for now, I would be extremely helped if someone presents a way of using the blob in php instead of string. Thank you.
Specifying b tells mysqli to send the data in separate packets to the server.
Documentation here
However, what the documentation fails to detail is how you should specify the packet data. One would assume, like the other types, you should just set up a referenced variable containing the data. It turns out you need to use send_long_data
With this function you actually have control over each chunk of data, so it's up to you to make sure you don't send a packet too large for your server to handle.
Try something like this
$stmt = $conn->prepare("INSERT INTO data_store (eid, ekey, ecipher) VALUES (?, ?, ?)");
//Initialise variables
$eid = $postedID;
$ekey = NULL;
$ecipher = NULL;
if($stmt->bind_param("sbb", $eid, $ekey, $ecipher)) {
// Send blobs
$ekey_chunks = str_split($postedKey, 8192);
foreach ($ekey_chunks as $chunk) {
$stmt->send_long_data(1, $chunk);
}
$ecipher_chunks = str_split($postedCipher, 8192);
foreach ($ecipher_chunks as $chunk) {
$stmt->send_long_data(2, $chunk);
}
$stmt->execute();
$stmt->close();
}
$conn->close();
Source this blog
By according to this question I have 2 table Source and details .
The Source table is as follows:
+----+----------+---------------+-----------+
| id | item_name|items_download | category |
+----+----------+---------------+-----------+
| |
+----+----------+---------------+-----------+
The details table is as follows:
+------+----------+-----+------+
| name | download | time| ip |
+------+----------+-----+------+
| |
+------+----------+-----+------+
At first step I want to get data from Source table (in real time) and put into details table by this code:
$get= "INSERT INTO `details` (`name`, `download`) SELECT `Source`.`item_name`,`Source`.`items_download` FROM `Source`"
At next step I want to get visitor IP address for each file.
for example if someone downloaded testfile I want to have this output:
+----------+---------+--------------+-----------+
| name | download | time | ip |
+----------+----------+-------------+-----------+
| testfile | 32 |download time|192.168.0.0|
+----------+----------+-------------+-----------+
| file2 | 0 | | |
+----------+----------+-------------+-----------+
To do this i use this code:
$ip = $_SERVER['REMOTE_ADDR'];
$update = "UPDATE details SET ip = '$ip', dldate = NOW()"
But its happened for all files, all of the file get same IP and time. I know its need a condition WHERE but I don't know what should I type as a condition to get IP address for each file that download.
Imho you don't need any UPDATE query. You just do an INSERT everytime a user requests a file:
<?php
$fileid = $_GET['fileid'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$sql = "SELECT * FROM Source WHERE id=" . (int)$fileid;
foreach ($pdo->query($sql) as $row) {
$statement = $pdo->prepare("INSERT INTO details (name, download, time, ip) VALUES (?, ?, NOW(), ?)");
$statement->execute(array(
$row['item_name'],
$row['items_download'],
$_SERVER['REMOTE_ADDR'],
));
}
?>
Some hints on the code above:
Use prepared statements - never inject any value directly into an SQL string.
It might be useless to insert file_name and items_download into the details table everytime. You have this information in your table "Source" anyway. So usually you would just put Source.id into your details table.
You should use your id column, which you have in your first table view, but it stragely disappears in the later ones.
Your id column should also be your PRIMARY_KEY AUTO INCREMENT column. Then each row has its own unique and indexed id.
But aside from that, what do you use to identify which file the user downloads? If it's the filename then simply use that:
EDIT: Add an id column to your details table!
$update = "UPDATE details SET ip = '$ip', dldate = NOW()
WHERE name = '$fileNameValue' LIMIT 1"
On a related note, you can not update multiple columns with the same shorthand reference of device = ip = '$ip' you have to specify each column in isolation and with an absolute target data to insert (here, the variable) .
If this is a typo you should edit and update your question.
Please also see Gerfried's answer regarding using prepared statements, they are the way you should be doing these things.
I think you need to get the session of user when he downloads the file and add it to the WHERE condition.
I have a table
id | entry | field | value
1 | 1 | name | Egon
2 | 1 | sname | Smith
3 | 1 | city | Los Angeles
4 | 2 | name | Stephe
5 | 2 | sname | Mueller
6 | 2 | city | New York
where id is the PK and autoincrements. Lines with the same entry belong together, they are kind of a dataset. I want to add new lines for a new entry (which should have the value 3).
My Question is: how can I obtain the next value for entry in a way, that it is unique?
At the moment im using something like
SELECT MAX(entry)+1
but when two queries are made at the same time, I'll get entry = "3" for both of them. I'm coding in PHP.
Use the sequence that you already got as a unique identifier at INSERT (don't leave this task to PHP):
INSERT INTO "my_table" ("entry", "field", "value") VALUES (currval(('"my_current_id_sequence"'::text)::regclass), 'any_field_info', 'any_value_info');
This way postgres will use the right number EVERYTIME.
Another aproach is to create a sequence and use it on INSERT as well, just use nextval(('"my_new_sequence"'::text)::regclass) as the value of entry and you can even use it as a default value.
If you need to know which value was used just add RETURNING entry to your INSERT
CREATE SEQUENCE alt_serial START 101;
ALTER TABLE "my_table"
ALTER COLUMN "entry" SET DEFAULT nextval(('"alt_serial"'::text)::regclass);
INSERT INTO "my_table" ("entry", "field", "value") VALUES (DEFAULT, 'any_field_info', 'any_value_info') RETURNING entry;
you can do some kind of loop that increments the entry every loop. If you want to add more lines with the same entry, pass more arguments to it in 1 loop.
class foo{
protected $foo = [];
public function set_foo($arguments = []){
$this->foo = $arguments;
}
public function insert_rows(){
$entry = // last entry from the db (number)- your logic here
$num_of_foos = count($this->foo);
$i = 0;
$query = 'INSERT INTO table(entry, field, value ) VALUES';
while($i<$num_of_foos){
if($i>1){$query .= ',';} // adds the comma if loop repeats more than once
$query .= '("';
$query .= $entry; // entry number for the first item
$query .= ',' . $this->foo[$i] . ',' . $some_Value;
$query .= '")';
$i++;
} // end of while loop
$entry++;
} // end of function insert_rows()
} // end of class foo
//now all you need to do is set the foo
$foo = new foo;
$foo->set_foo('lalala'); // sets one argument with new entry
$foo->set_foo('jajaja'); // sets another argument with new entry
$foo->set_foo('lala', 'jaja'); // sets two arguments with the same entry
You need to:
create a sequence
CREATE SEQUENCE table_entry_seq;
Then, when you need to add a row with a new entry, get the next value of the sequence:
SELECT nextval(('"table_entry_seq"'::text)::regclass)
I'd like to insert a multidimensional array into a MySQL Database field so that it can then easily be read from the database at a later date back into an array. What's the best way to achieve this?
I've tried the following to no avail:
$id = "MXB-487"
$items = Array(Array("Coffee", "Blend", "500"), Array("Coffee1", "Blend1", "250"));
$items = implode(",", $items);
mysqli_query($con,"INSERT INTO carts (id, items)
VALUES ($id, $items)");
/*Code that pulls the array from the Database based on id and stores in variable $info*/
restored_mdarray = explode(",", $info);
ID in MySql, is usually unique (I'm pretty sure you specified it that way). So, you can't share the ID for multiple items. Also, imploding will end up with the following query:
INSERT INTO carts (id, items) VALUES(MXB-487, Array, Array)
Because you have a multidimensional array you're trying to implode, it doesn't recursively implode.
What you should do is loop through the objects, and I'm not sure how the relationship here works, but it looks like you need a relation table to connect those items. Consider the following structure:
Carts:
+----------+-----------+
| ID | Name |
+----------+-----------+
--<-| MXB-487 | Blah blah |
| +----------+-----------+
|
| Items:
| +----------+-----------+----------+-----------+
| | Cart_ID | Type1 | Type 2 | Amount |
| +----------+-----------+----------+-----------+
--->| MXB-487 | Coffee | Blend | 500 |
+----------+-----------+----------+-----------+
And in order to implement that in PHP, you'd do something like this:
<?php
$id = "MXB-487";
$items = array(
array("Coffee", "Blend", "500"),
array("Coffee1", "Blend1", "500"),
);
$sql = "INSERT INTO actions (cart_id, type1, type2, amount) VALUES ";
$items_sql = array();
if (count($items)) {
foreach ($items as $item) {
$items_sql[] = "('$id', '{$item[0]}', '{$item[1]}', '{$item[2]}')";
}
}
$sql .= implode(", ", $items_sql);
And then run the query.
It will look like this:
INSERT INTO actions (cart_id, type1, type2, amount) VALUES ('MXB-487', 'Coffee', 'Blend', '500'), ('MXB-487', 'Coffee1', 'Blend1', '500')
Which you can later select as such:
<?php
$id = "MXB-487";
$sql = "SELECT * FROM actions WHERE (cart_id = '$id')";
Though as a side note, I suggest you look at PDO and how to bind values, or at least learn to escape your values in the SQL to prevent future injections.
I speculated the structure of the tables, of course you can modify to your needs.
To connect the tables properly via SQL (to fasten the fetching later on) you can use FOREIGN KEY when you define the table:
CREATE TABLE actions (
id INT(11) NOT NULL AUTO_INCREMENT,
cart_id VARCHAR(32) NOT NULL,
type1 VARCHAR(32) NOT NULL,
type2 VARCHAR(32) NOT NULL,
amount INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (cart_id) REFERENCES carts(id)
)
Use serialize:
$a = array(array(1,2,3), array(3,4,5));
$b = serialize($a);
# write $b to and later read $b from database
$c = unserialize($b);
$a == $c # => true