The main idea is being able to controll, upload and delete a slideshow's images from a database.
So, first I connect to the database like this, and with a while function I echo all the images I have stored in my db.
This is the code to do that:
<?php
$servername = "myservername";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT id, img FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src=".$row['img'].">";
}
} else {
echo "0 results";
}
?>
In the table "mytable" I have 2 columns: an ID auto-inc and a column called img.
How can I store an image in the img column so that my function will echo all the images I have in my table?
All I found searching til now was a lot of methods that upload the image with an html form, but I'd prefer to upload my img directly on my database, without building an html+php form to upload all my images to my table.
Is that possible?
Storing entire images in a database is generally a bad idea. It is much simpler to simply store the path of the image inside your database, as has already been mentioned. You may have a bit of extra work deleting the images, as you would need a php system call to delete the image file.
If you really must store images inside a database, you can save them as base64 encoded text. I've seen this be done at a fairly successful company, but no particularly good reason was given for this. Your sql execution time will be substantially larger, because images are large files, and your table size will balloon.
Related
Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}
I am working with a coupon code website, it has a products section. Instead of pulling data from API server of shopping sites every time a visitor loads the page, I want to store the data in SQL and use it..
But the data should update every hour or only if an hour is passed.
cron job is not required as I dont want to happen it automatically.
If there is 100 webpage users in an hour, they will get the same data, but when the first user comes after 1 hour time, it should overwrite the products's information in SQL.
I got the following code from w3schools.com and it work fine for saving data in SQL.
I hope some can help me to overwrite data only if it the data older than 1 hour. Otherwise it should act as "data already exists".
<?php
$servername = "localhost";
$username = "nuser";
$password = "pass";
$dbname = "db";
$ProductId = "smartphone";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$check=mysqli_query($conn,"select * from testdb where productid='$ProductId'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0) {
echo "Data Already Exists";
} else {
//insert results from the form input
$sql = "INSERT INTO Flipkart (productid, title, price)
VALUES ('productid','title','price')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();}
?>
The above code saves data in database, it can also detect duplicate data. but I want to add just one more function, which will overwrite data if the current data time is older than 1 hour. database has a TIMESTAMP "reg_date" column, which stores created date and time in YYYY-MM-DD HH:MM:SS format.
I am new to SQL and php, so pardon me if there is any problems with the question...
You can use a cron job.
This is the best explanation with code for PHP I have found so far for cron job:
https://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428
I am currently working on a project which will sell a product to a user, and on checkout completion, the user will enter an email address. I have been trying (but to no avail so far) to use MySQL to put this data into a database. Only in a certain way. I need the input data to use the UPDATE method to be put into an already existing row. This row should match the following criteria. It should not have already been used, the email should not already exist within the database. I have tried so many different pieces of MySQL, I get all sorts from syntax errors to it updating every record in my table, I have gotten as far as it updating just one, but not checking if it already exists. I was hoping for a little insight as to how I can improve!
Code as follows:
<?php
$servername = "localhost";
$username = "Josh";
$password = "10584066";
$dbname = "customers";
// Get email address from input form
$Email = $_GET['keyword'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE list SET Email='$Email' , In_Use='1' WHERE In_Use='0' LIMIT 1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
header('Location: /liteservers/logon/wood.php');
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
So, as you can see. The code is working almost as intended, I just want it to also check to see IF the email is already in the database and if it is, perhaps add the time that it attempted to record a new email within the same row as the already found existing email. I hope this actually makes sense if you need any more info that I haven't provided, let me know!
Use INSERT ON DUPLICATE KEY UPDATE syntax and mysql_affected_rows will tell you if its and insert or update.
I am trying to create a upload.php which uploads only PDF, DOC and DOCX to the database (path) and a file on my server. Now my upload to the file is working but I do not really know how to upload the link(path) to my table row.
Also the file I am uploading has to be able to be download by a click on a button on a detail page.
My upload.php
<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "persons";
// CREATE A CONNECTION WITH THE DATABASE
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_FILES["cv"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else
{
move_uploaded_file($_FILES["cv"]["tmp_name"],"files/" . $_FILES["cv"]["name"]);
echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";
$file="files/".$_FILES["cv"]["name"];
$sql="INSERT INTO person (person_cv, path) VALUES ('','$file')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";
}
mysql_close();
?>
The database name is called "persons" which has a table called person. The file link should save to person_cv. I am new to PHP and I am trying to understand PHP however there are so many ways to do it because of that I am getting confused.
You are confused of database structure too, as I see.
I don't know what data you really want to keep in database, but you need following:
table with basic data (called for example people_id), where you will have for example
id
name and surname
cv_file_id
table with file info
file_id (values must be the same as in cv_file_id)
name (may be exact name of file as was before uploading, or rather changed for better manipulation)
type (dfefined mostly by extension, like doc, docx, txt or so)
and probably also some other tables for informations of people, themselves
And in domain folders you will have one, where you will keep all uploaded cv files. And then, you will update db tables as needed - and also upload those files.
That is the most reasonable way how to do it. I would do it in this way. May it be that someone more experienced would do it in else way.
I'm trying to display an image from a MySQL database and my code works fine if the image is a JPG, but if I modify the content-type to display a PNG, it doesn't work...
How do I make it work for PNG??
<?php
// configuration
require("../includes/config.php");
header('Content-type: image/JPG');
$username = "xxxxx";
$password = "*****";
$host = "localhost";
$database = "database";
#mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
#mysql_select_db($database) or die("Can not select the database: ".mysql_error());
$query = mysql_query("SELECT * FROM images");
while($row = mysql_fetch_array($query))
{
echo $row['image'];
}
?>
Also, is it possible to display the image along with its name and description?
Thanks!
If you don't mind not supporting older browsers, you can use data urls to display your images and a description http://en.wikipedia.org/wiki/Data_URI_scheme.
<figure>
<img src="data:image/png;base64,<?php echo base64_encode($row['image']); ?>" alt="Your alternative text" />
<figcaption>Some more description</figcaption>
</figure>
Saving images in a database is not very useful in almost all cases. You should be carefull with upper and lower letters in the mimetype, see http://de.selfhtml.org/diverses/mimetypen.htm (it's german, but you will be able to read the list). And as a last advice - look at the mysqli_* functions http://www.php.net/manual/en/book.mysqli.php.
// Edit: Just an idea, but if you have multiple images in the database your image might be broken, because you just put them all into one image. This will not work! With your code, you can only display one image at once.