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')");
Related
I coded a function in PHP, which posts information of upload into a database table. If someone uploads a file, I will get the DateTime of the upload and his account number but I have an issue with the file name because the user is allowed to upload more than 1 file.
fdatum is Datetime
fmandantnr is User Number
fdateiname is Name of the file
The code is like following:
datensenden_copy.php
<?php
session_start();
require("../../require.php");
$omy= new clsMYSQL();
$output = '';
$fmandantnr=$_POST['fMandnr'];
for($i=0;$i<count($_FILES['userfiles']['name']);$i++) {
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
}
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
echo $query;
$omy->Query($query);
?>
I did my research and found out I need to get this:
for($i=0;$i<count($_FILES['userfiles']['name']);$i++){
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
}
Into this:
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
because the code cant get fdateiname in the SQL statement
Thank u for ur time.
You are looping over the $FILES array and getting the filename, but your INSERT command is OUTSIDE the loop so you only do ONE INSERT, with data from the last occurance in the loop. So simply move the insert inside the loop
In your code $fdatum does not appear to be defined anywhere, I hope/assume that was just left out of the sample code you gave us, or maybe it is created in the require.php code
<?php
session_start();
require("../../require.php");
$omy= new clsMYSQL();
$output = '';
$fmandantnr=$_POST['fMandnr'];
for($i=0;$i<count($_FILES['userfiles']['name']);$i++) {
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
$omy->Query($query);
}
?>
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
As I dont know anything about your clsMYSQL(); I cannot recode this to correctly use prepared statement.
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'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.
I'm having a problem with my personal server where I'm trying to create a database for the decade old binders I have for the Yu-Gi-Oh! Trading Card Game (haven't played in years). In testing the INSERT INTO, I keep running across a particular problem...
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Magic'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('Post', 'Post ' at line 1
Now my code outputs properly when I comment out the query function and echo to my webpage, but I keep getting the above mysql_error() message being displayed.
My code snippet is as follows...
if(isset($_SESSION['username'])) {
mysql_connect("localhost", "my_username", "my_password") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());
function clean_string($value) {
if(get_magic_quotes_gpc() ) {
$value = stripslashes($value);
}
return mysql_real_escape_string($value);
}
$Show = clean_string($_POST['show']);
$Table = clean_string($_POST['table']);
$Insert_M_T = $_POST['insert_magic_traps'];
$Insert_Monster = $_POST['insert_monster_effect'];
$Insert_Card_Type = clean_string($_POST['I_Type']);
$Insert_Card_Name = clean_string($_POST['I_Card_Name']);
$Insert_Description = clean_string($_POST['I_C_Description']);
$Insert_Card_ID = clean_string($_POST['I_Card_ID']);
$Insert_CardPack = clean_string($_POST['I_C_Pack']);
$Insert_PackID = clean_string($_POST['I_C_P_ID']);
$Insert_Quantity = clean_string($_POST['I_C_Quantity']);
if(isset($Insert_M_T)) {
$sql = "INSERT INTO '$Insert_Card_Type'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')";
mysql_query($sql) or die(mysql_error());
echo "<center><h2>Record added to Table: $Insert_Card_Type</h2></center>";
echo "<center><table><tr><th>Name:</th><td>$Insert_Card_Name</td></tr><tr><th>Description:</th><td>$Insert_Description</td></tr><tr><th>Card ID:</th><td>$Insert_Card_ID</td></tr><tr><th>Pack:</th><td>$Insert_CardPack</td></tr><tr><th>Pack ID Number</th><td>$Insert_PackID</td></tr><tr><th>Quantity:</th><td>$Insert_Quantity</td></tr></table></center>";
}
?>
//more html and php code
<?php
} else {
echo "<h1><center><font color=#ff0000 >ACCESS DENIED!!!</font></center></h1>";
echo "<h2><center><a href=index.php >Login Here!</a></center></h2>";
}
?>
Any advice would be helpful. I've tried searching for how to get around this problem, but to no avail. I feel like this is a simple fix, but I'm missing it. Please advise.
Thank you in advance.
~DanceLink
INSERT INTO `$Insert_Card_Type` (Name, Description, Card_ID, Pack, P_ID, Quantity)
VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')
Backticks around $Insert_Card_Type, not single quotes.
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.