Right now I am inserting blob files into a database. I have read up on the update syntax for mysql I can not figure out how to modify my code to update a row with the BLOB instead of inserting a new row with the BLOB. Could someone help me with this?
Here is my code:
<?php
// Create MySQL login values and
// set them to your login information.
$username = "root";
$password = "";
$host = "localhost";
$database = "test";
$tbl_name="members";
// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO members ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
1° You need to pass a referecence for what Data you are trying to update, like the Primary Key Id From Table.
2° Update SQL should be like it
$image = mysql_real_escape_string($unsafe_image);
$id = mysql_real_escape_string($unsafe_id);
$query = "UPDATE members SET image = '$data' WHERE id_image = $id";
$results = mysql_query($query, $link);
Related
This question already has answers here:
PHP: How to check if image file exists?
(22 answers)
Closed 5 years ago.
Can someone please help me to make this script check if the file exists, before it truncate the table.
If filename not exists, I want to stop the import.
<?php
//set the connection variables
$hostname = "host";
$username = "username";
$password = "pass";
$database = "database";
$filename = "filename.csv";
//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));
mysqli_query($connection, "TRUNCATE TABLE `my_tablename`");
// open the csv file
$fp = fopen($filename,"r");
//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
//insert csv data into mysql table
$sql = "INSERT INTO Pristabell (Produkt, Pris, Rabattkr, Rabattprosent, Lagerstatus, Butikk, TAGS) VALUES('" . implode("','",$row) . "')";
if(!mysqli_query($connection, $sql))
{
die('Error : ' . mysqli_error($conection));
}
}
fclose($fp);
//close the db connection
mysqli_close($connection);
?>
Thanks :-)
http://php.net/manual/en/function.file-exists.php
if(file_exists($pathtofile)){
//do import
}else{
//stop
}
One simple solution is use
file_exist;
in an if() chunk.
Before the while(), if true continue else exit or trow an exception.
This is my code to generate csv file.When I click php button to generate Csv file,which is filled withthe contents based on the category column from the database.But my problem here is when the contents are getting populated twice in the csv file as shown below.Please help to out where i have to modify the code so that i can get only one time populated content as shown below as expected.Thanks in advance.
createcsv.php
<?php
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stats";
define("DB_SERVER", "localhost");
define("DB_NAME", "stats");
define("DB_USER", "user");
define("DB_PASSWORD", '');
$dbconn = #mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
$conn = #mysql_select_db(DB_NAME,$dbconn);
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "DB connection failed";
}
// Query DB to fetch hit count for each category and in turn create corresponding .csv file
function createCSVFile($type) {
$msql = "SELECT TRIM(TRAILING '.000000' from UNIX_TIMESTAMP(hitdate)*1000) as unixdate,count from h_stats where category='".$type."' order by unixdate asc";
$query = mysql_query($msql);
$type = str_replace(' ', '', $type);
$tmp_file = "data/tmp_".$type.".csv";
$fp = fopen("$tmp_file", "w");
// Write the query contents to temp file
while($row = mysql_fetch_array($query))
{
fputcsv($fp, $row);
}
fclose($fp);
// Modify the contents of the file as per the high chart input data format
$fp = fopen("$tmp_file", 'r+');
rewind($fp);
$file = "data/".$type.".csv";
$final = fopen("$file", 'w');
while($line = fgets($fp)){
trim($line);
$line = '['.$line.'],';
fputs($final,$line);
}
// Append var $type and remove the trailing ,
$final = file_get_contents($file);
$content = 'var '.$type .'= [' . rtrim($final, ","). ']';
file_put_contents("$file",$content);
}
// Query DB to fetch success/failure count for Hits and in turn create corresponding .csv file
function createHitOutcomeCSVFile($type,$category) {
$sql = "SELECT TRIM(TRAILING '.000000' from UNIX_TIMESTAMP(hitdate)*1000) as unixdate,".$type." from h_stats where category='".$category."' order by unixdate asc";
$query = mysql_query($sql);
$tmp_file = "data/tmp_".$type."_".$category.".csv";
$fp = fopen("$tmp_file", "w");
// Write the query contents to temp file
while($row = mysql_fetch_array($query)){
fputcsv($fp, $row);
}
fclose($fp);
// Modify the contents of the file as per the high chart input data format
$fp = fopen("$tmp_file", 'r+');
rewind($fp);
$category = str_replace(' ', '', $category);
$file = "data/".$type."_".$category.".csv";
$final = fopen("$file", 'w');
while($line = fgets($fp)){
trim($line);
$line = '['.$line.'],';
fputs($final,$line);
}
// Append var $type and remove the trailing ,
$final = file_get_contents($file);
$content = 'var '.$type.'_'.$category.'= [' . rtrim($final, ","). ']';
file_put_contents("$file",$content);
}
// Invoke function to create the Hits.csv file
createCSVFile('Hits');
// Invoke function to get Three Hits csv file
createHitOutcomeCSVFile('TCount','Hits');
// Invoke function to get O2 Hits csv file
createHitOutcomeCSVFile('BCount','Login');
echo "Generated successfully";
?>
not expected csv file with twice populated data:
var Login_Hits= [[1427826600000,1427826600000,8763,8763
]]
Expected csv file as per highcharts format:
var Login_Hits= [[1427826600000,8763
]]
Try to debug it...
it will be easier than seeing typo or so...
it looks like the tmp file is already corrupted...
try to display the $row variable and the $query...
the problem may come from here...
In while loop I have used mysql_fetch_assoc instead of mysql_fetch_array at both the functions
while($row = mysql_fetch_assoc($query))
{
fputcsv($fp, $row);
}
The content is not repeating twice in the Csv file.This works try it!
I am trying to replace one pdf that previously upload in MySQL to another pdf . I created an a href [edit] for user to choose the pdf file and link to editDB.php where query update placed.
This is edit.DB.php
<?php
// Connect to the database
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="is"; // Database name
$tbl_name="publication"; // Table name
if(isset($_POST['submit']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$conn = mysql_connect("$host", "$username", "$password");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
Connect database, fetch file_id, fetch other data that updated
$conn = mysql_connect("$host", "$username", "$password");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if (isset($_GET["id"]))
{
$id =$_GET["id"];
}
else
{
echo'failed';
}
mysql_select_db($db_name);
$title=mysql_real_escape_string($_POST['title']);
$author=mysql_real_escape_string($_POST['author']);
$year=mysql_real_escape_string($_POST['year']);
$abs=mysql_real_escape_string($_POST['abstract']);
query here
$query="update publication set title='".$title."', author='".$author."', year='".$year."' , abstract='".$abs."', file_name='".$fileName."', file_size='".$fileSize."', file_type='".$fileType."', content='".$content."' where file_id='$id'";
mysql_query($query) or die(mysql_error());
echo '<script type="text/javascript">alert("'.$title.' updated!");
window.location.href="publication.php";
</script>';
mysql_close($conn);
}
?>
The problem I faced is that , after I key in updated info in my edit form. The data successfully direct to editDB.php. pop up dialog showing data updated is shown but the data did not updated both database and the page showing info. I will be grateful for any help hands. Thanks.
Instead of
if (isset($_GET["id"]))
{
$id =$_GET["id"];
}
else
{
echo'failed';
}
i change it to
if(isset($_POST['submit'])&& $_FILES['userfile']['size'] > 0)
{
$id =$_POST["id"];
Of course the id must pass properly and make sure id is match with ur database.
This code can works. Hope able to help you all.
I am building a simple website, I want to allow the users to upload and change their avatars. At present I have been able to upload images to a mysql database, stored as blobs with the code as follows:
//connected to DB, userID fetched
$image = $FILES['fileToUpload']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql = "UPDATE tbUsers SET profileImage = '".$content."' WHERE userID = ".userID;
$result = mysql_query($sql) or die (mysql_error());
When I download the files from phpmyadmin after upload they are saved as .bin files, but can be viewed normally. I'm not sure if this is correct or not.
My code to display the images is as follows:
HTML:
<?php echo '<img src ="showPic.php?q='.$_SESSION['profile'].'"/>'; ?>
PHP:
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
header('Content-type: image/jpeg');
$row = mysql_fetch_object($result);
echo $row['image_data'];
}
I am unsure if I am attempting to display the image in the correct way, any help (corrections/alternative solutions) would be greatly appreciated :)
You can do this :
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
$content = mysql_result($result,0,"file_content");
$name = mysql_result($result,0,"file_name");
$type = mysql_result($result,0,"file_type");
$size = mysql_result($result,0,"file_size");
header("Content-type: $type");
echo $content
}
Note : You should have these column in you table where you save your BLOB data
file_name = for save filename
$_FILES['file']['name']
file_type = for save file type
$_FILES['file']['type']
file_size = for save file size
$_FILES['file']['size']
You select this
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
and refer to not selected column
echo $row['image_data'];
I have an image submission form that just uses a simple action="" to get to a PHP page that adds the submission details to the DB and creates a unique page for the submission. That works fine. However, I want it to redirect to their submission page (created with fwrite()) How would I do this? Code below.
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "templates/";
$submissions_path = "submissions/";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_GET['right_form_title'];
$filename = $_GET['right_form_url'];
$submitter = $username;
$type = exif_imagetype($_GET['right_form_url']);
list($width, $height) = getimagesize($filename);
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
$php_file_name = $name.".php";
$path_for_link = $submissions_path.$php_file_name;
$tpl = file_get_contents($tpl_path.$tpl_file);
$tpl_and_values = preg_replace("(%([a-z_][a-z0-9_]*)%)ie",'$$1',$tpl);
$fh = fopen($submissions_path.$php_file_name, "w");
fwrite($fh, $tpl_and_values);
fclose($fh);
?>
Adding this after you close the file would work just fine.
header('location: '.$submissions_path.$php_file_name);
I believe all you need to do is stick a header at the bottom of that file which will redirect to the newly created file. Try adding this at the bottom of your file.
header('Location: '.$submissions_path.$php_file_name);