Writing ForEach Loop to database - php

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')";

Related

how to add multiple records in mysql using php?

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.

PHP - Check for distinct filename on file upload

I'm pretty new to PHP. I hate to have to ask questions, because I'm sure this is documented somewhere, but after looking for a while, I just cannot seem to put two and two together.
I have a program that will allow multiple images to be uploaded to an item within the database. Basically, for each item in the database, there might be multiple image uploads.
Example:
Item: Xbox 360
Images:
Xbox360.jpg
side.jpg
front.jpg
The image and item information is all stored in the database (MySQL), but the images are stored within the filesystem, and the database points to the URL of the image(s) in the filesystem.
The problem I'm having is that everything works as expected, except it allows duplicate image names to be written to the database. It doesn't allow duplicate images to be written to the filesystem, which I'm happy with. I want to make sure that the name of an image is only added once to the database. If the image name is a duplicate to another, it needs to not write to the database.
add_db.php:
$uniqueDir = uniqid();
$directory = "img/$uniqueDir/";
db_addItem($id_category, $name, $cost, $description, $qty, $directory); //Adds to the `items` table
foreach ($_FILES['i_file']['name'] as $filename) {
if ($filename != '' && $filename != 'No file chosen') {
//I think above is where I check for unique image names
$url = "img/$uniqueDir/$filename";
db_addImg($url, $filename); //Adds to the `img` table
$item_picsID = get_item_PicsID($filename, $url);
$itemID = get_itemID($directory);
db_insertImg($itemID, $item_picsID);
}
}
addFilesystem($directory); //Writes image(s) to filesystem
function db_addImg($url, $filename) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO img (`name`, `url`) VALUES(:filename, :url)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':filename' => $filename,
':url' => $url
));
}
function db_insertImg($itemID, $item_picsID) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO `item_pics` (`item_id`, `img_id`) VALUES(:itemID, :item_picsID)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':itemID' => $itemID,
':item_picsID' => $item_picsID
));
$db = null;
return;
}
Everything works, except it will write duplicate image names to the database. I want the image names to be distinct. I also don't want to rename the images (if possible).
You can define an UNIQUE index on the name column in img table, and then use slightly modified INSERT statement in your db_addImg function:
function db_addImg($url, $filename) {
//...
$query = "INSERT INGORE INTO img (`name`, `url`) VALUES(:filename, :url)";
//...
}
It will quietly cancel any insert where the is a UNIQUE key collision, which will end up in distinct filenames across your img table.
I would use a filename based on the primary key from the img table as you're guaranteed it's unique.
Otherwise, you'll need to guess a unique filename with some type of hashing and then check the file system. All of which can be expensive operations.
Looks like you are using PDO, so the static method lastInsertId will get the last insert id (primary key).
For example:
// after your insert to img
$filename = 'img' . $db->lastInsertId() . $extension;
This will require changing the img table slightly. But you're better off storing meta data (file type, size, etc) in this table as opposed to the file location (as that can change).
I think better to use hash value of your url as the primary key. Be cause string searching is much slower as int.

What is wrong with this ezSQL query?

I am trying to use this simple query on a website I am working on but it is not inserting any data into the database!
<?php
// Include database configuration
include('../config.php');
// Include ezSQL core
include_once "ezSQL/ez_sql_core.php";
// Include ezSQL database mysql component
include_once "ezSQL/ez_sql_mysql.php";
// Initialise database object and establish a connection
$db = new ezSQL_mysql($db_user,$db_pass,$db_database,$db_host);
$the_file = "video.mp4";
$the_image = "image.jpg";
$the_title = "Title";
$the_description = "lokr dry ceyrc cetcn cebtyn cetbny rnyfb rybrnr rybynum nyr";
$the_anime = "Anime";
$the_genre = "Genre";
$the_slug = "anime";
$db->query("INSERT INTO video (file, image, title, description, anime, genre, slug) VALUES ($the_file, $the_image, $the_title, $the_description, $the_anime, $the_genre, $the_slug)");
$db->debug();
?>
Please help me a bit here!
since the values that you want to insert are strings you should try something like this:
$db->query("INSERT INTO video (file, image, title, description, anime, genre, slug) VALUES ('$the_file', '$the_image', '$the_title', '$the_description', '$the_anime', '$the_genre', '$the_slug')");
all non-numeric column requires quote
$db->query("INSERT INTO video (file, image, title, description, anime, genre, slug) VALUES ('$the_file', '$the_image', '$the_title', '$the_description', '$the_anime', '$the_genre', '$the_slug')");

INSERT INTO using PDO not inserting data

I am trying to get the data to insert into the specified database but it just wont. Ive looked at the manual tried examples and all of that but I cant get the data to pass through to the database I can however echo/print_r/var_dump it so I know I have data. Here is my code:
public function insertJson($url, $subId)
{
$json_file = file_get_contents(KHAN_BASE.$url.'/videos');
if(isset($json_file))
{
$json_decoded = json_decode($json_file, true);
}else{
$this->error = 'A valid JSON file was not specified';
}
// var_dump($json_decoded); <--- This return all of the data needed from the json pull so i know I have data
//m3u8, mp4, png,
//". $row['m3u8'] .",". $row['mp4'] .",". $row['png'] .",
foreach($json_decoded as $row)
{
//echo $row['backup_timestamp'].'<br/>'; <--- This outputs the correct information so I know I can access it that way
$sql = "INSERT INTO tbl_khan_videos (sub_subject_id, backup_timestamp, date_added, description,
duration, extra_properties, has_questions, ka_url, keywords, kind, position, readable_id, relative_url, title, url, views,
youtube_id) VALUES (:subid, :backup_timestamp, :date_added, :description, :duration, :extra_properties, :has_questions, :ka_url, :keywords, :kind, :position,
:readable_id, :relative_url, :title, :url, :views, :youtube_id)";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":subid", $subId);
$stmt->bindValue(":backup_timestamp", $row['backup_timestamp']);
$stmt->bindValue(":date_added", $row['date_added']);
$stmt->bindValue(":description", $row['description']);
$stmt->bindValue(":duration", $row['duration']);
$stmt->bindValue(":extra_properties", $row['extra_properties']);
$stmt->bindValue(":has_questions", $row['has_questions']);
$stmt->bindValue(":ka_url", $row['ka_url']);
$stmt->bindValue(":keywords", $row['keywords']);
$stmt->bindValue(":kind", $row['kind']);
$stmt->bindValue(":position", $row['position']);
$stmt->bindValue(":readable_id", $row['readable_id']);
$stmt->bindValue(":relative_url", $row['relative_url']);
$stmt->bindValue(":title", $row['title']);
$stmt->bindValue(":url", $row['url']);
$stmt->bindValue(":views", $row['views']);
$stmt->bindValue(":youtube_id", $row['youtube_id']);
$stmt->execute();
}
}
Im not sure what I am doing wrong. I have tried binding it as an array (ex: $array = array(':subId' => $subId); $stmt->execute($array);) and still get no data through to the database. I know my config for the $this->db is good because I can pull other forms of already populated data with it. Any help would be very much appreciated.
I figured out my problem through some of the advice on here. What had been happening is I was trying to bind null values so the bindValue would cause the execute to go through without producing an error. Simple fix was doing this through foreach loops with a couple if statements which allowed me to set a value to the fields that were null. This solved the error. Again thank you to those who attempted to set in the correct path to finding the solution.

PHP mysql insert associative array into database from a "dynamic" form

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]));
}
?>

Categories