Deleted from comma separated list in MySQL table - php

I have a comma separated list stored in one row in a column in a mysql database (eg. phrase1, phrase2, phrase3, phrase4). I want to write a query that will deleted one of the values from that comma separated list, say 'phrase3', and its comma, making the list (phrase1, phrase2, phrase4). Ideas?
The list is generated with the following code if that helps:
$q6 = "UPDATE post SET denied_user = CONCAT_WS(', ',denied_user,'$claimer_id'), denied_time = CONCAT_WS(', ',denied_time,NOW()) WHERE post_id = '$post_id' AND user_id='$user_id' AND denied_user<>'' AND denied_user NOT LIKE '%$claimer_id%' AND post_status='active";

Related

Getting Different ID Values in one table with DISTINCT query

My table in the DB
As you can see i have a table contain several IDs including Survey_survey ID and Store ID, i want to get all the Store IDs and their Survey_surveyIDs without duplicates.
Here is what i have tried
$getSurvey = mysqli_query($dbConnection , "SELECT DISTINCT Survey_surveyId FROM maintable");
while ($row = mysqli_fetch_array($getSurvey)) {
$getStoreIDS = mysqli_query($dbConnection , "SELECT DISTINCT Stores_storeID FROM maintable WHERE Survey_surveyId=".$row['Survey_surveyId']."");

Get values from CSV file and search MySQL database

I have a query a Wordpress include which does the following:
$sql = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'merchant_id' LIMIT 6";
$results = $wpdb->get_results($sql);
foreach ($results as $row)
{
echo $row->meta_value . ",";
//sprintf("SELECT * FROM retailers WHERE advertiserId = '%s'", $row->meta_value);
}
//clean all results
$wpdb->flush();
It parses all pages custom fields (merchant ID numbers), and returns any unique distinct values, separated by a comma. This bit works great.
ie: The above may return: 1301,345,723,134,1435
What I also have is a separate MySQL table of about 20 fields, three of which are the MerchantID, programmeName, and commissionMax. Each value from the CSV correlates with the MerchantID in the database.
Regardless of the amount of merchant ID's that appear in the CSV - I need to parse them all, but show the three highest commission rates (commissionMax), as well as the programmeName.
I managed to get connected to my external database and retrieve the appropriate values (using the commented code above) however this showed all of the retailers information.
Any advice?
Use the following query with limit:
SELECT * // select all fields
FROM table_name // from your table
WHERE MerchantID IN (your_ids_here) // IDs received from previous query or wherever
ORDER BY commissionMax DESC // descending sort by commissionMax field
LIMIT 3 // take first 3 results

PHP - search using 2 concatenated fields

I've concatenated 2 fields in a form's drop down list, with the 2 fields being First Name and Last Name; This allowed me to display a person's full name.
The issue is that in the database a person's full name is stored in 2 seperate fields; First Name and Last Name.
I need to match the person's full name (from the dropdown list) to the First Name and Last Name in the DB, however I am struggling to achieve this.
The php code for the concatenated form list is:
<td>
<select name='IndivSurname'>";
while($FullName_row = odbc_fetch_array($sql_run_FullName)){
$IndivFirstName=$FullName_row['FirstName'];
$IndivLastName=$FullName_row['LastName'];
echo"<option value='$IndivIndivId' . '$IndivTenantNdx'> $IndivFirstName $IndivLastName</option>";
}
</select>
</td>
While the SQL statement is:
SELECT EventId, EventTime, Individual, Tenant, TenantName, DeviceName, Comment,
InetDb.dbo.Individuals.FirstName, InetDb.dbo.Individuals.LastName
FROM taclogdata.dbo.Event
LEFT JOIN InetDb.dbo.Tenants
ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
LEFT JOIN InetDb.dbo.Individuals
ON taclogdata.dbo.Event.Individual = InetDb.dbo.Individuals.IndivId
AND taclogdata.dbo.Event.Tenant = InetDb.dbo.Individuals.TenantNdx
WHERE (taclogdata.dbo.Event.EventTime BETWEEN '00:00:00 05/26/2015'
AND '09:00:00 05/26/2015'
AND (taclogdata.dbo.Event.Comment ='Reader entry'
OR taclogdata.dbo.Event.Comment='Reader exit')
AND (InetDb.dbo.Individuals.FirstName = '$IndivFirstName'
AND InetDb.dbo.Individuals.LastName = '$IndivLastName')";
Many thanks in advance
The easiest way to do this, is by splitting the string on the space. However, that introduces a bug if the person has more than one first- or surname. This means that in the cases where we have 3 or more elements in the result of the split, we'll have to add the middle elements to both matches; Seeing as we don't know whether it's a surname or middle name.
That is why I recommend using a different character for the glue in the value attribute, one which is never used in a name. # is one such character.
This leaves you with the following code for the form-generation:
// CF: Added HTML-escaping to prevent XSS-attacks.
$IndivFirstName=htmlspecialchars ($FullName_row['FirstName']);
$IndivLastName=htmlspecialchars ($FullName_row['LastName']);
echo"<option value='{$IndivFirstName}#{$IndivLastName}'> $IndivFirstName $IndivLastName</option>";
In the SQL-statement you can do the following (using prepared statements):
$stmt = $db->prepare ("SELECT EventId, EventTime, Individual, Tenant, TenantName, DeviceName, Comment, InetDb.dbo.Individuals.FirstName, InetDb.dbo.Individuals.LastName
FROM taclogdata.dbo.Event
LEFT JOIN InetDb.dbo.Tenants
ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
LEFT JOIN InetDb.dbo.Individuals
ON taclogdata.dbo.Event.Individual = InetDb.dbo.Individuals.IndivId
AND taclogdata.dbo.Event.Tenant = InetDb.dbo.Individuals.TenantNdx
WHERE (taclogdata.dbo.Event.EventTime BETWEEN '00:00:00 05/26/2015' AND '09:00:00 05/26/2015'
AND (taclogdata.dbo.Event.Comment ='Reader entry' OR taclogdata.dbo.Event.Comment='Reader exit')
AND (InetDb.dbo.Individuals.FirstName = :firstname AND InetDb.dbo.Individuals.LastName = :lastname)");
$name = explode ("#", $_POST['IndivSurname']);
$stmt->exec (array (":firstname" => $name[0], ":lastname" => $name[1]));
Splitting on spaces is not going to be reliable given the number of De Aches and Mc Pains in this world.
The really sure way of doing this is to save the first name and last name in a hidden table within your form (in the same order as your pulldown).
A possible alternative is to concatenate using a not a space but one of the other white space characters like NO BREAK SPACE "\u00A0" which you can then reliably split later.
Ok I solved my problem by POSTing the user's PK rather than his First Name and Last Name individually, and search using those characteristics.
However I introduced the explode function as per the below to separate the concatenated values as per the below:
SQL query selects the IndivId, TenntNdx, individual's first name and last name, however only the first name and last name of the user are displayed in the form's drop down list. The matching IndivId and TenantNdx are posted using the code below:
$sql_FullName = "SELECT IndivId, TenantNdx, FirstName, LastName FROM InetDb.dbo.Individuals
ORDER BY FirstName ASC";
$sql_run_FullName = odbc_exec($conn_general, $sql_FullName);
while($FullName_row = odbc_fetch_array($sql_run_FullName)){
$IndivIndivId = $FullName_row['IndivId'];
$IndivTenantNdx = $FullName_row['TenantNdx'];
$IndivFirstName=$FullName_row['FirstName'];
$IndivLastName=$FullName_row['LastName'];
echo"<option value='$IndivIndivId $IndivTenantNdx'> $IndivFirstName $IndivLastName</option>";
The code above would POST the IndivId and TenantNdx (which form a composite primary key for the individuals table) to the page containing the code below which would then separate the 2 fields and search by the PK rather than the individual's name:
$IndivSurname = $_POST['IndivSurname'];
$explode_sql = explode(" ", $IndivSurname, 2);
$ListIndivId = $explode_sql['0'];
$ListTenantId = $explode_sql['1'];

How can I insert a list of numbers into a MySQL table?

I need to insert a list of comment IDs into a column liked_comments.
For example if a user likes comments with IDs 72, 839, 37, then they will be stored in there.
$id = mysqli_real_escape_string($conn,$_POST['id']); // a number posted using ajax from another file
$username = mysqli_real_escape_string($conn,$_SESSION['username']);
if (!empty($_POST) && isset($_SESSION['username'])){
mysqli_query($conn,"UPDATE users SET liked_comments=liked_comments+$id WHERE username='$username'");
}
At the moment this just adds the IDs as though they were numbers rather than strings, but I need it to be 71,789,173 or 71 789 173 separated by a space or comma. Adding +' '+ or +','+ didn't seem to work.
You cannot concatenate using + in mysql, you have to use concat like
$Query = "UPDATE users SET liked_comments=concat(liked_comments, ',', '$id') WHERE username='$username'";
Also, Instead of storing comma separated values in column, you can move comments part to separated table, where each row contain PostID and UserID, that would be much neater and flexible.
The best way to do this would be to store arrays inside the database. For example; if we have this array:
$liked_comments_array = array(71, 789, 173);
You can store it in the array like so:
$liked_comments_array = serialize($liked_comments_array);
// now insert this into the database
Then when you fetch this array from the database, simply unserialize it like so:
$liked_array_comments = unserialize($field_from_database);

Update MYSQL and SET particular row Content

I am trying to update my table t1 which has rows as following :-
id
menu
Currently i am having data in it as
id = "1"
menu = "menu1 ,menu2 ,menu3, menu4"
I am using explode method of PHP to get MENU row of my table t1.
$show_data = mysql_query("SELECT menu FROM t1");
$showrow = mysql_fetch_assoc($show_data);
$showmenu = $showrow['menu'];
$pieces = explode(",", $showmenu);
Now I want to delete content menu3 from row MENU ,
Please provide me which query should i use , UPDATE , ALTER or DELETE.
You should store your menus in a separate table, linked to this one by a unique identifier.
Then edit that table in the usual way.
It is better to separate $menu1 $manu2 $menu3 and $menu4
You can implode() them as a single $string with \t separator
and Insert it to Mysql.
When nessesary,select the field from table
explode() it to separate strings using \t separator
remove the $menu3 variable frome being imploded this time
again implode() them
and UPDATE the field

Categories