I have a mysql database with a table in the following format:
ID: 1
Date: 2010-12-19
Image: 5d61240f-7aca-d34b-19-12-10-15-36.jpg
Caption: Merry Xmas
I want to create a php script which checks through each row in this table and checks that the image is present in a gallery folder on my server. If the image is not in the gallery folder then I want to delete this row from my database. Some pointers on how to go about doing this would be very much appreciated.
Thanks!
try
<?php
define ("GALLERY_ROOT", "/path/to/gallery/" );
$mysqli = new MySQLi ($host, $username, $password, $db);
$result = $mysqli -> query ("
SELECT
id,
image
FROM
table
");
if ( $result ){
while ($row = $result->fetch_assoc()) {
if ( !is_file (GALLERY_ROOT . $row['image'] ) ){
$mysqli -> query ("
DELETE FROM
table
WHERE
id = '" . $row['id'] . "'
LIMIT 1
");
print "Deleted " . $row['id'] . "<br />";
}
}
$result -> free();
}
$mysqli -> close();
print "Congratz!! All invalid rows has been deleted!";
?>
That was a quick one, i didn't try running it actually.
Also if you have a lot of rows, then you might want to rethink about selecting all the rows at once. But again get back to me on how it works
Ok... use glob() or the DirectoryIterator, file_exists(), the mysql_ or mysqli_ functions, and 'DELETE FROM images WHERE id = ?'. :)
Hope this helps! If you supply some more information, I could give you more detailed advice. What have you tried so far?
EDIT: wait, I misread. You don't need the directory functions, as you already have the filename. dirname(__FILE__) might be useful.
Related
Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}
I've figured out how to display info submitted into mysql, but I haven't figured out how to keep the past info there. It's going to show the current post on top and keep adding on top everytime new info is submitted but only display like 10 posts at a time. I hope I am explaining this well.
How to go about doing this, I am completely lost. I've connected to the database and everything and now im to:
echo $hit, $amount, $category;
and stuck. that is displaying the info submitted, but when i submit new info, that info changes and the past info is gone. My question is, how would i get the past info to stay and get the new info to build on top of past info?
Thanks.
Edit: here's more of the code. also, ive been told about mysqli. i just havent changed it yet.
if(!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('can not use' . DB_NAME . ': ' . mysql_error());
}
$hit = $_POST['hit'];
$amount = $_POST['amount'];
$category = $_POST['category'];
$sql = "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')";
$result = mysql_query($sql);
if(!mysql_query($sql)){
die('Error: ' . mysql_Error());
}
echo $hit, $amount, $category;
mysql_close();
?>
After the insert sql you need to do a select query to retrieve all the rows from the database as you are only echoing the currently set values.
You need to also be mindful of sql injection as the values you're adding to the database are not sanitised in any way. Use a command such as mysql_real_esape_string or htmlentities for this.
Before the line echoing the results...
echo $hit, $amount, $category;
You need to have a select query combined with a while loop and the mysql_fetch_array or mysql_fetch_assoc commands to output the rows from the database. A first check is to see if the records are being added to the table.
At no point in your code are you fetching data from the database. You're simply submitting the data from the form to mysql, and displaying it at the same time.
You can fetch data from mysql by doing something like this:
$data = mysql_query("SELECT hit, amount, category FROM hit");
// Adding MYSQL_ASSOC as a second argument tells mysql_fetch_array that
// we want an associative array (we can refer to fields by their name, not just by number)
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
echo '<p>'
.'Hit: ' . $row['hit']
.', Amount: ' . $row['amount']
.', Category: ' . $row['category']
.'</p>';
}
Keep in mind this is all a simplified version of things, and it needs more work, especially on security. I should probably be using htmlentities() here, depending on the data. And you should definitely be protecting against SQL injection if that data is coming directly from a user.
I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli
i am relatively new to php. I have a problem with displaying images in my browser ( google chrome) after retrieving blob data from mysql database.
Basically the following code works when the slashes are added in front of the echo at the bottom. However i have followed other online tutorials and the tutor has been able to display their images without the use of slashes whilst i am unable to get the image up. I just wondered what the standard rule is? Another thing to add - when i do fail to get the images up in the browser i get instead a ting thumbnail. I would really appreciate if anybody could tell me how to reliably display images. The site i wish to create is just about images. So its kind of fundamental. Thanks a lot in advance for your time.
<?php
$conn = mysql_connect ("localhost","root","arctic123");
$db = mysql_select_db ("user_images", $conn);
if(!$db) {
echo mysql_error();
}
$q = "SELECT * FROM images";
$r = mysql_query ("$q",$conn);
if($r) {
while($row = mysql_fetch_array($r)) {
//echo $row ['username'];
//echo "<br>";
header ("Content-type: image/jpeg");
echo $row ['logo'];
//echo "<br>";
}
}else{
echo mysql_error();
}
?>
You can't have header after any output in your code: http://php.net/manual/en/function.header.php
Best practice is to upload images to a directory and just store the image's path/file name in the database. Also makes it easier to manipulate the image, e.g. create different sizes and thumbnails with PHP. And it takes about four times less the disk space...
Hope you are not storing your images on MySQL, please if you do, desist from that detrimental act because it is going to make your database unnecessarily heavy...
I would recommend not storing your images in a database. While it is technically possible, it has serious performance concerns. Best practice would be to designate a folder for the images, then access them directly. If you'd like the filtering and sorting ablities of MySQL, then replace the BLOB column that currently stores the image data with a VARCHAR containing the file name.
<?php
$conn = mysql_connect ("localhost","root","arctic123");
$db = mysql_select_db ("user_images", $conn);
$imgdir = "/path/to/image/directory/";
if(!$db) {
echo mysql_error();
}
$q = "SELECT * FROM images";
$r = mysql_query ("$q",$conn);
if($r) {
while($row = mysql_fetch_array($r)) {
echo $row['username'];
echo "<br>";
echo "<img src='" . $imgdir . $row['logo'] . "' />";
echo "<br>";
}
}else{
echo mysql_error();
}
?>
I have a MySQL database full of user information, like their username, password, email, etc.
I want a PHP script that allows me to pull JUST their username and display it like so:
"username1","username2","username3"
Literally exactly like that, the quotes and all.
EDIT: Sorry for not supplying enough information.
The table is named "users" the field I want to pull off it is "username" I can get it to pull and display all the information, my only problem is imploding it.
OK dude, read the comments
<?php // open a php tag
$dbc = mysql_connect("host", "username", "password"); // connect to database
mysql_select_db("db_name", $dbc) // select the database
$sql = "SELECT `username` FROM `users_table`"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$username_array[] = "\"".$row['username']."\""; // get the username field and add to the array above with surrounding quotes
}
$username_string = implode(",", $username_array); // implode the array to "stick together" all the usernames with a comma inbetween each
echo $username_string; // output the string to the display
?>
I've seen all the other answers, however have you considered using PDO instead of mysql_query functions? It's a much nicer way to work with the database.
Here's what you want to achieve in a few lines of code (using lamba functions):
$dbh = new PDO("mysql:host=localhost;dbname=test", "yourusername", "yourpassword");
$results = $dbh->prepare("SELECT u.username FROM users u");
$results->execute();
$results = $results->fetchAll();
echo implode(", ", array_map(function(&$r) { return $r['username']; }, $results));
Output: Jamie, Bob, Chris
Nice and clean. Also, you should check if you have any results that have been returned and if the query was successful.
Just another approach.
EDIT: I've just realised you're a beginner so my answer may be a bit too advanced. However, i'll leave it for others to see as a solution, and perhaps you might look into using PDO an lamba functions when you learn a bit more. Best of luck.
Let's assume that you have a 'mydb' database and 'users' table in it.
SQL needed:
USE mydb;
SELECT username from users;
Short version:
Wrap it in PHP calls to mysql PHP library
Get result as an array then implode it with comma symbol.
Long version:
First we need to connect to database:
$db = mysql_connect('DATABASE_HOST', 'USER', 'PASSWORD');
if (!$db) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('mydb', $db);
if (!$db_selected) {
die ('Can\'t use mydb: ' . mysql_error());
}
Remember to always check the return values of functions.
Then we query the database:
$result = mysql_query('select username from users', $db);
...and fetch results in flat array (we need only usernames):
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC))
{
$data[] = $row['login'];
}
Then we format the returned data according to your specs:
$string_result = '"'. implode('", "', $data) . '"';
You can do with $string_result anything you want, just close the database connection immediately after use:
mysql_close($db);
Good luck with learning PHP, BTW. ;)
You could using PHP's implode, but it's probably easier just do it in SQL assuming that the list won't be too long:
SELECT GROUP_CONCAT(CONCAT('"', username, '"')) AS usernames
FROM your_table