add to a mysql column instead of replacing? - php

I want to add an extra value to a mysql table column, e.g:
the field 'photos' already has an image name in, but i want to add another image name into the field using php.
I thought INSERT would just add it in on top but it seems to replace the existing image name. I want to avoid selecting the current field values, adding the new value and re-inserting if possible.
thanks!
code:
php:
$query = "INSERT INTO `listings-rent` (photos) VALUES ('$fileName') WHERE id = '$insertID'";
mysqli_query($mysqli, $query);
the problem is this replaces the existing value in the 'photos' column, rather than adding to it

It is highly discouraged, to keep multiple values in the same column. But it is, of course possible.
UPDATE `photos` SET imagename = CONCAT(imagename, ",", $second_name) WHERE id=$insertID'
You will then use explode in PHP to get an array of strings like:
array("image1.jpg", "image2.jpg")

You insert with a WHERE statement. This will not work.
try:
$query = "INSERT INTO `listings-rent` (photos,id) VALUES ('$fileName', $insertID)";
mysqli_query($mysqli, $query);

Related

Using PHP array to search a column in SQL DB that is separated by commas

I have a column in my DB labeled providers. This column can have multiple values, i.e (1,2,3,4,5) or (14,2,9,87). I have an array that is also filled with similar values i.e (1,9,7,3) and so forth.
I am trying to query my DB and return results from the table where any of the values in the variable array match the values split by commas in the column.
This is what I have.
$variable = "1,9,3,4";
$sql = "SELECT id, provider FROM table_name WHERE FIND_IN_SET(provider, '$variable')";
However, this is not working. If the column in the DB has more then one value, it returns nothing. If the column only has one value, it returns it fine.
I'm not sure, but LOCATE should solve your problem.
Example:
$sql = "SELECT id, provider FROM table_name WHERE LOCATE('$variable', provider) = 1;";
but not works if order of ids is different.
The CSV should be the second parameter of your find_in_set. The first should be the single value you are searching for. So you should split $variable into multiple values. Something like this:
$variable = "1,9,3,4";
$values = str_getcsv($variable);
foreach($values as $value) {
$sql = "SELECT id, provider FROM table_name WHERE FIND_IN_SET($value, provider)";
//execute $sql here
}
should do it.
With your previous approach the find_in_set was looking for 1,9,3,4, not 1, 9, 3, or 4, as you had wanted. The manual also states the behavior using the function that way won't work.
This function does not work properly if the first argument contains a comma (,) character.
You should update the table in the future when you have time so it is normalized.

How to add a possble value to a MySQL SET type in php, without know the current values

Hi everybody and sorry for my english.
I have the column "example" that is a SET type.
I have to make a php page where you can add values to that column.
First of all I need to know what is just in "example", to prevent the adding of an existing value by a control. Second of all I need to add the new value.
Here's what I had thinked to do.
//I just made the connection to the db in PDO or MySQLi
$newValue=$_POST['value']; //I take the value to add in the possible values from a form
//Now I have to "extract" all the possible values. Can't think how.
//I think I can store the values into an array
$result=$sql->fetch(); //$sql is the query to extract all the possible values from "example"
//So now i can do a control with a foreach
foreach($result as $control){
if ($newValue == $control){
//error message, break the foreach loop
}
}
//Now, if the code arrives here there isn't erros, so the "$newValue" is different from any other values stored in "example", so I need to add it as a possible value
$sql=$conn->query("ALTER TABLE 'TableName' CHANGE 'example' 'example' SET('$result', '$newValue')"); //<- where $result is the all existing possible values of "example"
In PDO or MySQLi, it's indifferent
Thanks for the help
We can get the column definition with a query from information_schema.columns
Assuming the table is in the current database (and assuming we are cognizant of lower_case_table_names setting in choosing to use mixed case for table names)
SELECT c.column_type
FROM information_schema.columns c
WHERE c.table_schema = DATABASE()
WHERE c.table_name = 'TableName'
AND c.column_name = 'example'
Beware of the limit on the number of elements allowed in a SET definition.
Remove the closing paren from the end, and append ',newval').
Personally, I don't much care for the idea of running an ALTER TABLE as part of the application code. Doing that is going to do an implicit commit in a transaction, and also require an exclusive table / metadata lock while the operation is performed.
If you need a SET type - you should know what values you add. Otherwise, simply use VARCHAR type.

how to check mysql for duplicates with php

I need a way to check a database if a word is in it already if so then it doesn't have to be pushed to the database if the word isn't in it yet then it has to be pushed into it.
It's a MYSQL database and I have to do it in PHP this is what I got so far.
$result = array_count_values(explode(" ", $filter));
arsort($result);
foreach ($result as $word => $frequency)
{
if (!in_array($word, [" ", ""]))
query("words", "INSERT INTO Woord (woord) VALUE (?)",[$word], false);
}
query("words" "SELECT WHERE")
You have 2 options:
REPLACE
REPLACE INTO table
SET column = 'example'
This will overwrite if the record exists and if not it will create it.
INSERT IGNORE
INSERT IGNORE INTO table
SET column = 'example'
This will ignore the query if already exists and if not it will create it.
Your php query should look like this:
"INSERT IGNORE INTO ID142118_ascii.Woord (woord) VALUES (".$word.")"
put a unique constraint on the column "woord" in the table.
Then you can let your php script insert as many duplicate words as you want to, it will simply fail.
you could either add a part "ignore duplicate" in your query or just ignore the error you will get.
I thinks that will be easiest to do.
edit:
btw I can think of a lot of words containing serveral of the character you are stripping: "foto's", "zee-eend" etc
--
how to make a unique index:
ALTER TABLE asciiwoorden
ADD UNIQUE INDEX somename (Woord);

php image update query, how to update the query

Exampe list view:
Example of edit view:
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
$sql = "INSERT INTO imgexam
(image, name)
VALUES
('{$imgData}', '{$_FILES['userfile']['name']}');";
How to change the query, so it will update the current image instead of inserting a new one?
So what you have to do to update it to the new image is the following steps:
Remove old image Upload
new image Update the row in the database to
the name of the new image
How to remove old image using PHP:
unlink('directory/images/'.$image);
You might need to do a selection from the database to get the right image name.
How to upload new image using PHP:
Read this page for more informations on uploading files
Then after uploading the new image, you need to change the row in the database.
How to change the row in the database
$sql = "UPDATE FROM `table` SET `imagename` = '$newimagename' WHERE `imagename` = $oldimagename";
$query = mysql_query($sql) or die(mysql_error());
Thats is the steps you need. Ask if you have problems.
The SQL query you're looking for to update a record would be similar to this:
UPDATE imgexam SET image = ? WHERE name = ?;
If you have duplicate names, you'll want to retrieve the ID for the record and use that in the WHERE clause. You can get the ID with a method like PDO::lastInsertId() or by querying for it.
What you may also be looking for is sometimes called an UPSERT operation. This means I want to UPDATE or INSERT. MySQL provides an ON DUPLICATE KEY clause. Let's assume ID is your primary key for this table.
Change your query to read
INSERT INTO
imgexam (id, image, name)
VALUES (1, '{$imageData}', '{$_FILES['userfile']['name']}')
ON DUPLICATE KEY UPDATE
image = '{$imageData}';
Update query for BLOB things:
mysql_escape_string() just treats the string as raw bytes, and adds escaping where it believes it's appropriate.
$query = "UPDATE mytable SET blobthing = '" .mysql_escape_string($varblobthing) .
"' WHERE id=2";

Auto increment wont update

just created a form that saves the filename into an SQL database.
The thing is that when I ad the ID column(Auto increment) into the SQLDatabase the form stops to save my filename, but as soon I delete the ID row, it begins to save.
Dont know whats the problem.
this is some of my code
<?php
if(isset($_FILES['file_name'])) {
$file_name = mysql_real_escape_string($_FILES['file_name']['name']);
//Writes the information to the database
mysql_query("INSERT INTO `files` VALUES ('$file_name')") ;
}
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM files") or die(mysql_error());
//Puts it into an array
?>
And my database has two columns file_id and file_name
but as I just wrote, the file_id wont work =/
Any ideas ?
I think you need to change your SQL query to this:
mysql_query("INSERT INTO `files` (`file_name`) VALUES ('$file_name')") ;
With more than one column, you need to name which column you want the $file_name string to be saved in if you're not going to enumerate every column in the table. Then your auto-increment should work fine.
In fact, the problem isn't with auto-increment, it's with your SQL syntax. You should check your queries for errors by saving the return value from mysql_query and checking if it returned false. If it did, call mysql_error to determine the error message.
Since ID is auto_inc, you don't need to include it in your script anywhere.
I think the problem is because you don't specify in your query what fields to put the values in.
Change this:
mysql_query("INSERT INTO `files` VALUES ('$file_name')") ;
To something like this
mysql_query("INSERT INTO `files` (`YOURFIELD`) VALUES ('$file_name')") ;

Categories