for example i have an array of images of a specific location lets say of new york...which i want to store in mysql... these images are coming directly from wikipedia...how can i insert these images in a loop with each image entry would get the same location name?..like this
1|Newyork|img1.jpg
2|Newyork|img2.jpg
3|Newyork|img3.jpg...so on...
what i have done so far is..
foreach($images as $record)//'$images' is the array of images..
{
$sql="INSERT INTO `search`(`id`, `name`, `image`) VALUES ('','".$data"','".$record."',} //$data is the name of location
if I understood well, even if I don't see your array, sth like that would be the query loop:
//if id is a primary key autoincrement
foreach ($images as $data => $record){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$data."','".$record."') ");
}
but most possibly the array is of that form
for($i=0; $i<count($images); $i++){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$images[$i]['data']."','".$images[$i]['record']."') ");
}
It depends of the array form.
Related
I would like to embed a query in a stored procedure. The query to be embedded, however, is carried out within a foreach cycle because the values are transmitted from a form.
This is the snippet, in PHP:
<?php
foreach ($preferences as $preference) {
$sth = $db->prepare('INSERT INTO preferences (preference, user_cod) values (:preference, :user_cod)');
$sth->bindValue(':preference', $preference);
$sth->bindValue(':user_cod', $user_cod);
$sth->execute();
}
?>
How can I pass the array as a parameter to the stored procedure to execute the same query several times within the foreach loop in the stored procedure?
To give an example, the stored procedure would be structured like this:
BEGIN
INSERT INTO users (name, surname) values (name_in, surname_in);
INSERT INTO images (image, user_cod) values (image_name_in, user_cod_in);
FOREACH preferences AS preference
INSERT INTO preferences (preference, user_cod) values (preference_in, user_cod);
END FOREACH;
END
Thank you in advance for any help given! I'm very new to PHP and would love some advice/help! i want many id fields separated by comma to be inputted into a database separately with the same resource id variable.
Find a link to a picture here! Here, a user enters many ids for the name, and only one ID for the resource, I would like all ids to be entered into the database with the same resource id beside it
//so this is creating the array to split up the ids
$array = explode(",", $id);
//finding length of array
$length = count($array);
//now we want to loop through this array, and pass in each variable to the db
for ($x = 0; $x < $length; $x++) {
$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id)
VALUES ($id [$x], $resource_id)"
$result = mysqli_query($dbcon,$sqlinsert);
}
I think it could be something like this code above but it doesnt seem to be working for me...
In short i want a user to enter many ID fields and only one resource field, and for this to be inputed into the database separately. I hope this makes sense!
Thanks again for any help given!
To only answer your question and not questioning your database schema. Have a look at the following code:
$ids = explode(",", $id);
$inserts = array();
foreach ($ids as $id) {
$inserts[] = "($id,$resource_id)";
}
$query = "INSERT INTO ids_to_resources (id,resource_id) VALUES " . implode(',', $inserts) . ";";
You can insert multiple rows in one sql query by seperating them with a comma. The code should generate a query like this:
INSERT INTO ids_to_resources (id,resource_id) VALUES (1,4),(2,4),(3,4);
You would be better off creating a separate table which has a new row for each record... the columns would be ID, NINJA_ID, RESOURCE_ID. Then insert it that way. Put an Index on RESOURCE_ID. This way you can easily search through the database for specific records, updating and deleting would be a lot easier as well.
But if you insist on doing commas,
$comma_ids = implode("," $array);
You don't have semicolon after this line and you musnt't have a space between $id and [$x]
$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id)
VALUES ($id[$x], $resource_id)";
I'm currently working with the $_FILES array, however I am wondering how it would be possible to insert values into a single cell within the database as an array after each of the specified objects within that array have been modified.
My code below has taken all of the ['tmp_name']s and added a randomized six digit value before the name of the file. The purpose for this is to prevent any images from being overwritten if the same file path is inserted by other users.
As I cannot place the array as it is into the database, what I would like is for each of the modified ['tmp_name']s to be placed back into an array, then inserted into the database with their new values. I'd then like to know how to grab the array from the database cell and put it back into a while loop to display on another page.
Thanks in advance, Rich
Here is my code so far, if anyone could shed some light on how I could achieve this it'd be much appreciated:
$i = 0;
$countFiles = count($_FILES['upload1']['tmp_name']);
while ($i < $countFiles) {
$imgName1 = preg_replace("#[^a-z0-9.]#i", "", $_FILES['upload1']['name'][$i]);
$imgName1 = mt_rand(100000, 999999).$imgName1;
move_uploaded_file($imgTmp1[$i], "images/$imgName1");
$i++;
}
$sql = "INSERT INTO articles (title, articleContent, date, image) SELECT '".$title."', '".$articleContent."', now(), '".$imgName1."'";
$res = mysql_query($sql);
You can use serialize() to store arrays in database
$arr = array(1, 2, 3);
$str = serialize($arr); // Store the string in db
To get back the array use unserialize()
$arr = unserialize($str);
Hope this helps
This is a stupid question, but I can't seem to find an answer.
I have a foreach loop, that finds all the images on a particular link. I would like to encode all those images, and then write them to the database. If I put the sql query inside the foreach loop, then a new row is created for every images, if I put the sql query outside the foreach loop, only the first image is written. If I try to write the images and the rest of the data separately, the insert sees $newimage as null and overwrites the values. Any advice would be appreciated?
foreach($html->find('img') as $images) {
$newimage = json_encode($images->src);
echo $newimage;
}
$sql="INSERT INTO data (headline, images, email, date, category, area, number, crawled, lastcrawled, description)
VALUES ('$headline', '$newimage', '$email','$date','$category','$area','$number', '$crawled', '$dt', '$description')";
This should give you what you're looking for, based on your comment:
// create an array to hold the image sources
$store_images = array();
foreach($html->find('img') as $images) {
// add the image sources to the array
$store_images[] = $images->src;
}
// encode the entire array of images
$json_store_images = json_encode($store_images);
// store the encoded images along with the other data
$sql="INSERT INTO data (headline, images, email, date, category, area, number, crawled, lastcrawled, description)
VALUES ('$headline', '$json_store_images', '$email','$date','$category','$area','$number', '$crawled', '$dt', '$description')";
Hope this would be helpful to you.
$newimages = array();
foreach($html->find('img') as $images) {
$newimages[] = $images->src;
}
$newimage = json_encode($newimages);
Same sql then -
$sql="INSERT INTO data (headline, images, email, date, category, area, number,
crawled, lastcrawled, description) VALUES ('$headline', '$newimage',
$email','$date','$category','$area','$number', '$crawled', '$dt', '$description')";
I have a form that allows for the duplication of fields. The form is posted via php and inserted into a database. My problem is I cannot seem to loop through the array correctly. Am I setting up the form correctly (are the name's formatted correctly) and am I looping through the arrays correctly? I am not successful in getting any data inserted.
The trick is that the duplicated fields need to stick together.
Think of the fields as sets of questions and answers.
Each question has a title, the question text and a file input.
Each answer has a title, the answer text a file input, and a check box to note the correct answer.
I have the name's set up like so:
name='question[1][title]'
name='question[1][text]'
name='question[1][file]'
answer[1][title][]
answer[1][text][]
answer[1][file][]
answer[1][correct][]
The php to insert the form is as follows:
$insert_question = $db->prepare(
'insert into questions (title, text) values (?, ?)');
$insert_answer = $db->prepare(
'insert into answers (question_id, title, text, correct)'.
' values (?, ?, ?, ?)');
foreach ($_POST['question'] as $q_num => $q)
{
$insert_question->execute(array($q['title'], $q['text']));
$q_id = $db->lastInsertId();
//********************
// insert files
//********************
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
}
Sorry that this is such a huge question. I have been working on this for two days now and have run out of ideas.
I'm not sure I understood your problem (I don't speak english fluently).
But here you need an other loop instead of this one:
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
like :
$lim = count($_POST['answer'][$q_num]['title']);
for($i=0;$i<$lim;++$i){
$insert_answer->execute(
array($q_id, $_POST['answer'][$q_num]['title'][$i], $_POST['answer'][$q_num]['text'][$i], $_POST['answer'][$q_num]['correct'][$i]));
}
It didn't test anything and it should work only if you always get title, text and correct in an answer.
The issue is with the second loop (answer array). Try this
<?php
foreach ($_POST['answer'][$q_num]['title'] as $a => $value)
{
$insert_answer->execute(
array($q_id, $_POST['answer'][$q_num]['title'][$a], $_POST['answer'][$q_num]['text'][$a], $_POST['answer'][$q_num]['correct'][$a]));
}
?>