
|
View Full Version : mySQL apposition ID readings under PHP.
horizon 09-02-2006, 05:39 PM The following request might be one of the most complicated task I'm about to request. I have searched over this section on the forum to see if there were any results on this subject but none was not (at least - not - to what I'm specifically looking for).
Here's the thing.
I have created an HTML form with checkboxes, built an array - pointing to the targeted action under PHP, even imploded the array results. All is working well so far. I have even set the array, from the targered action, in order to get ready to clear the specific readings to be cleared out (deleted).
However, this works only with individual values for each SQL fields.
The way I'm trying to delete these entries is like the following:
user_id: 1,2,3,4,5,6,7 ...
and so on (so - all appositions from the same lines under a specific SQL table for each users.
As you can see, from the example above, I have '7' numbers. What I'd like to do is to delete, for example, two entries like this:
5,7
Now, what I'd like to do is to capture the rest of the IDs:
1,2,3,4,6
and be able to update / delete them to / from that field_id without having to re-import the cleared out fields (which I have been unsuccessful so far).
Is there anyway this could be done without affecting the whole row itself ? I have already tried using the 'NOT IN' command through the SQL statement but without success. The removed values keeps coming back on anyhow. I know I'm missing something but I'd like to know what could be the best solution to clear out these two readings for good.
Anyone who could help me on this would be greatly appreciated. :)
Thanks !
Saeven 09-02-2006, 06:01 PM I'm not sure I understand.
If you issue a query such as:
DELETE FROM table WHERE id IN ('5','7')
Then only 1,2,3,4,6 will remain.
horizon 09-02-2006, 07:00 PM It it were that easy, I would definitely figured that one out already. As I said, it is being initialized from a PHP array as this array contains the imploded IDs info in order to get rid of.
Althought, when I - either - delete / update the table, the deleted content is still included in the appositions. What I'm trying to do is actually getting rid of them and only keep the rest of the values (so - still - from the PHP array variable) that has NOT been deleted. ;)
Any ideas on how I could accomplish this ?
2detailed 09-02-2006, 10:10 PM unset them unset($array[id]) in the actual array.......
horizon 09-02-2006, 10:22 PM Yes. I tried that already but I need to update the SQL table by removing these values and leave the others on the specific fields. It does attack the right field but does not eliminate the selected values from the form. It removes all of them from that single field.
Any other solutions ?
2detailed 09-02-2006, 10:53 PM paste some code.
horizon 09-02-2006, 11:03 PM For the first time - since I use this forum - I don't even know what part could be posted since I'm all technicly ... misaligned with my codes so I don't even know where to start this time since it's the first time I'm trying something like this.
However, still technicly speaking, would it be possible to, may be, use the foreach statement and, then, eliminate these two values before re-inserting the rest of the valuable values into the field ?
Then, from the selected fields, would it - also - be possible to eliminate these two values before re-inserting the rest since there are huge chances (probably will) that these two values will easily get back to that field at the same time.
2detailed 09-02-2006, 11:05 PM Paste the section of code where it involves this issue, i.e. from where you are making the query, and wanting to change the arrays values.
horizon 09-02-2006, 11:16 PM Let's try this:
if (isset($_POST['user_id'])) {
$user_id = (isset($_POST['user_id']) && (is_array($_POST['user_id']))) ? $_POST['user_id'] : 0;
} else {
$user_id = 0;
}
if (!is_array($user_id)) {
die ('No permission');
} else {
$user_ids = implode(",", $user_id);
$sql = "
SELECT user_id
FROM table
WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$user_id_field = $row['user_id'];
}
$top_user_id_array = explode(",", $user_id_field);
if (!empty($user_id_field)) {
$sql_update = "
UPDATE table
SET user_id = '".$user_id_field."'
WHERE user_id IN (".$user_ids.") AND id = ".$_SESSION['user_id'];
$result = mysql_query($sql_update);
}
}
if ($result) {
header("Location: index.php");
}
Now, as you can see, there are some missing peaces from the puzzle for what I'm trying to accomplish. I just wonder if I could achieve what has been demonstrated from the first post. ;)
2detailed 09-02-2006, 11:36 PM So now what are you trying to do, are you trying to take away from the array of id's pulled from the database, based on what was posted, or vica versa?
horizon 09-02-2006, 11:40 PM are you trying to take away from the array of id's pulled from the database, based on what was posted
Almost there. Like I said, supposing you're selecting two IDs, from an HTML form with checkboxes, the array will actually capture the mount of IDs you're having (which, this part, works really well). What I'm trying to accomplish is to, yes, clear out these two selected fields + pulled them out from the database by updating / deleting (doesn't matter - both will be considered from the posted hopeful answer) and then keep the rest of the unaffected values into that field (so that only these two would be cleared out from the apposition).
I hope it is explained a little bit better this time, since I really look forward to see these codes. ;)
2detailed 09-03-2006, 01:48 AM I don't get why you are imploding a $_POST['user_id'], perhaps link me to your form as well. Also, looking at your code again, it appears you have things doing useless things, unless I'm just not seeing a part of the code, for example you are imploding $user_id_field, which, shouldn't this be a single id, or am I getting something wrong?
It appears you useless change from an array to a string, back to an array, and then back to a string, over and over for no apparent reason....
horizon 09-03-2006, 08:14 AM Could someone please post the right codes without having to create another page - or without posting critism - on this topic ???
2detailed 09-03-2006, 08:50 AM Trust me, I am the last person to criticize you on the matter, I am just trying to figure out exactly what you are trying to do, and give you a hand, but if that is how you see it, best of wishes.... but anyways what I *think you are trying to do....
<?php
if(is_array($_POST['user_id']))
{
// mysql query.
$query = mysql_query("SELECT user_id FROM table WHERE id = '" . $_SESSION['user_id'] . "'") or die(mysql_error());
// here we grab the mysql result set.
$user_id_field = mysql_result($query, 0);
// here we create an array $top_user_id_array by exploding $user_id_field by ',' delimiter.
$top_user_id_array = explode(",", $user_id_field);
// this is where I'm not sure what you want to do, because if it's empty, why would you explode it in the previous line?
if(!empty($user_id_field))
{
// second sql query to update the database
$query = mysql_query("UPDATE table SET user_id = '' WHERE user_id IN ('" . implode(',', $_POST['user_id']) . "') AND id = '" . $_SESSION['user_id'] . "'") or die(mysql_error());
// again here is where I am confused, because I don't know how you are controling the form, because you have not showed it to me, I don't know if you are using keys or values.
foreach($_POST['user_id'] as $key => $value)
{
// if keys
if(in_array($key, $_POST['user_id']))
{
unset($_POST['user_id'][$key]);
}
// if values
if(in_array($value, $_POST['user_id']))
{
unset($_POST['user_id'][$value]);
}
// or it could be mixed... not sure exactly what you are trying to do.
}
session_write_close();
header('Location: index.php');
}
}
?>
horizon 09-03-2006, 09:00 AM foreach($_POST['user_id'] as $key => $value)
{
// if keys
if(in_array($key, $_POST['user_id']))
{
unset($_POST['user_id'][$key]);
}
// if values
if(in_array($value, $_POST['user_id']))
{
unset($_POST['user_id'][$value]);
}
// or it could be mixed... not sure exactly what you are trying to do.
}
This block is the opposite of what I'm looking for. What I'm trying to do is to remove these two values from the user_id row. So, the $_POST['user_id'] variable contains these two values. With those two values, I'd like to remove them from the apposition that's inside the user_id row. I don't know how clearer it can be explained to you. No HTML form needs to be posted here. Simply a balance of PHP should suffice ...
As for this one:
$query = mysql_query("UPDATE table SET user_id = '' WHERE user_id IN ('" . implode(',', $_POST['user_id']) . "') AND id = '" . $_SESSION['user_id'] . "'") or die(mysql_error());
I do not wish to implode these two values - which is what is being specified here. I'd like to be able to exclude these two values from the user_id row (explained above) while updating / deleting the apposition in that row.
horizon 09-04-2006, 10:22 AM Any ideas on this one ?
2detailed 09-05-2006, 08:30 AM You really are not explaining what you are trying to do clear enough, so if you show the forum, show the results, and expected results, whether it be mysql data changing, or env var changing, show us. Also include a sample of the form, all of these aspects come into the design.
horizon 09-05-2006, 07:42 PM All theorical example has been posted under the first post on this topic. It is clairly well explained.
Saeven 09-05-2006, 08:04 PM 2detailed is right horizon, your examples and phrasing aren't very conducive to a solution. Apposition is too vague a word to use at that, it can mean juxtaposition, or an undefined syntactic relation. Please stop using that word. Your examples were hardly theoretical, they are practical voicings of something that still remains impractical. Please don't get mad at us because we don't understand, I myself am simply trying to help! I'm sure once we can properly extract what it is you are trying to do, it'll take me 2 seconds flat to suggest a solution.
This writ, let's get some factual info:
So far, what I can gather from your post is that you are able to construct an array of integers which represents MySQL table ids.
// imaginary hardcoded form input:
$array = array( 5, 7 );
From what I can gather, 5 and 7 (Set B) belong to a set of integers that represent row IDs in a MySQL database (Set U). You want to operate on all IDs but those in Set B.
What is it that you want to do on all IDs in U / B?
What do you mean by "could be done without affecting the whole row itself"? Insertion and deletion will not affect other row's contents, unless you are improperly using the TIMESTAMP column where you might instead want to be using DATETIME.
What I wrote in the second post, stands:
// assuming $dbconnection is your database connection, and that you are able to collect your integers as written
// your array values (hardcoded as example)
$arr = array( 5, 7 );
if( count( $arr ) ){
foreach( $arr as $id )
$idstr = "'{$id}',";
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
mysql_query( "DELETE FROM table WHERE id IN ($idstr)", $dbconnection );
}
This will delete all rows with IDs 5 or 7 in your table, and leave the remainder of rows, ex, those with id 1, 2, 3, 4, 6, 8
Alex
horizon 09-05-2006, 09:18 PM Apposition is too vague a word to use at that, it can mean juxtaposition, or an undefined syntactic relation.
Sorry there. Didn't even know these two words ever existed. I'm not even there yet. :eek:
I'm not mad - I'm simply stating facts.
As for this line,
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
I have to admit this wasn't implemented in my codes but ... may I ask what it does actually ? I have never use substr on the same line as strlen before. ;)
In the mean time, I will report shortly if this actually works.
horizon 09-05-2006, 09:31 PM // assuming $dbconnection is your database (http://www.webhostingtalk.com/showthread.php?t=544208&page=2#) connection, and that you are able to collect your integers as written
// your array values (hardcoded as example)
$arr = array( 5, 7 );
if( count( $arr ) ){
foreach( $arr as $id )
$idstr = "'{$id}',";
}
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
mysql_query( "DELETE FROM table WHERE id IN ($idstr)", $dbconnection );
}
There's a little bug actually. By looking at your codes, you - either - forgot to close the if statement or foreach statement at the end of your condition statement. ;)
Saeven 09-05-2006, 09:34 PM There is no bug there. Your suggestion correction is semantically false as well, why would you execute the codeblock if there was no array? You're prematurely closing it...and adding an extra } at the end!
// your array values (hardcoded as example)
$arr = array( 5, 7 );
if( count( $arr ) ){
foreach( $arr as $id )
$idstr = "'{$id}',";
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
mysql_query( "DELETE FROM table WHERE id IN ($idstr)", $dbconnection );
} // closes if( count( ...
Maybe you misinterpreted the quotes?
FYI, it's ugly code im(h)o to bracket single-line loops:
foreach( $arr as $id ){
$idstr = "'{$id}',";
}
// is syntactically equivalent yet less beautiful than
foreach( $arr as $id )
$idstr = "'{$id}',";
Indentation is a beautiful poetry :) I digress however!
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
This strips the last comma in the string of ids to be deleted.
horizon 09-05-2006, 09:37 PM Woops. About the foreach no-bug, sorry about that. I thought this was opened with a braket statement but seems not. ;)
This strips the last comma in the string of ids to be deleted.
Ahh ! excellent then. This is exacly what I was looking for. I will try this out immediately. :)
horizon 09-05-2006, 09:57 PM Unfortinutely, it doesn't work. It returns:
Invalid argument supplied for foreach() in . . .
(Note: . . . is, of course, the rest of the error line).
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')
The IN, from the SQL statement, has empty parentheses. It doesn't capture the $idstr variable.
And, yes, proper modifications were done by renaming the mySQL's table name + the id field. ;)
Any other idea ? :(
Saeven 09-05-2006, 09:58 PM I called my array $arr, what did you call yours?
horizon 09-05-2006, 10:01 PM I simply used the same name as you did. I even tested with mine as I have the same error result unfortunitely.
Saeven 09-05-2006, 11:48 PM then your $arr doesn't contain an array. Work on your collection..
horizon 09-06-2006, 06:24 AM As you can see from this post:
http://www.webhostingtalk.com/showpost.php?p=4083174&postcount=9
I'm, first, checking if the variable is, indeed, an array. If not, it fails. ;)
Any other idea ?
Saeven 09-06-2006, 10:57 AM That's a poorly scoped block of code.. Consider replacing it with these few lines:
if( isset( $_POST['user_id'] ) && is_array( $_POST['user_id'] ) ){
$user_ids = implode( ",", $_POST['user_id'] );
$result = mysql_query( "SELECT user_id
FROM table
WHERE id = '{$_SESSION['user_id']}'", $connection );
if( $row = mysql_fetch_assoc( $res ) ){
if( $row['user_id'] && count( $user_ids ) ){
$idstr = "";
foreach( $user_ids as $id )
$idstr = "'{$id}',";
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
mysql_query( "UPDATE table SET user_id = '{$row['user_id']}'
WHERE user_id IN ($idstr) AND id = '{$_SESSION['user_id']}'" ) or die( mysql_error() );
header("Location: index.php");
}
}
}
else{
die ('No permission');
}
There's some wierd stuff in your code that I assumed was a sematic mistake.
$sql = "
SELECT user_id
FROM table
WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$user_id_field = $row['user_id'];
}
Why loop through a set of records if only one result is returned, or constantly overwrite them if many results are returned? I assume that 'id' is a primary key on that table?
Nonetheless, this has nothing to do with an array error...you're probably not catching your array, or screening it properly. Get an IDE like Zend Studio, it can help you when you are learning with its "Analyze Code" feature.
horizon 09-06-2006, 12:52 PM Ok thanks. I will try this up later today. As for the while loop statement, good question for the single field. I was so into it that I forgot to tell myself to simply set a single variable without a loop. It would, indeed, of been enough. As for the user_id field as a primary - no - it isn't. It's being placed under the 2nd row in the table.
More inputs to come later . . .
horizon 09-06-2006, 05:44 PM This is, now, the error I got:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AND ...
I followed all the steps you posted. Any other suggestions ?
Saeven 09-06-2006, 07:38 PM Good luck! :) Hope this has jogged a solution for you.
horizon 09-06-2006, 07:45 PM Hope this has jogged a solution for you.
It ... didn't. Which is why, I posted back. :eek:
Ah ! well, I guess I will have to wait for an experienced PHP coder to post but I thank you for your time and try-outs anyway. ;)
Saeven 09-06-2006, 08:14 PM I think if you looked into my portfolio you wouldn't have resorted to such an insult. I could write quite a bit, but I'll desist here. What I posted were not 'try-outs' they were solutions. Your inability to apply them hardly constitutes a 'lack of experience' on my behalf.
Good luck, to anyone that adds to this thread!
horizon 09-06-2006, 08:17 PM Your inability to apply them hardly constitutes a 'lack of experience' on my behalf.
Then, perhaps, from the great experience you own already, perhaps you could post a definite solution, on this one, due to two server errors (since errors from server are rarely wrong) ?
Saeven 09-06-2006, 09:25 PM My snippets cannot generate the error you've noted. In candor horizon, I'd write that this isn't a popularity contest, I'm just here to lend a hand (it's my relaxation). You've been second guessing everything myself and anyone else has posted, down to an original finger pointing about parenthesization.
Post your entire .php file, and myself or someone else here will take a look I'm certain.
horizon 09-06-2006, 09:50 PM I'd write that this isn't a popularity contest
Yes, I'd have to agree on this one. In fact, it was quite expected this way but I was really looking for an answer.
I'm just here to lend a hand (it's my relaxation).
I'm not denying the fact that you're trying to assist towards an issue that seem to be harder than I thought to resolve. However, it has almost been three pages - instructed from the first post on what I was trying to accomplish but, unfortunitely, without success so far.
The entire PHP 'has' been posted entirely already. All I'm doing is renaming those variables into their appropriate names (to avoid copyrighting issues).
In addition to what has been technicly posted before, I have added an extra line with explode (to avoid further errors from the foreach statement - as posted above). Then, I used your foreach statement from the explode variable, rather than the implode variable, and the error doesn't show up anymore.
Althought, it still fails to update the info from the SQL statement. No errors are showing either. It simply returns to it's original page without any modifications over the fields. Everything simply remains as it is.
The good news is, when I uncomment the SQL UPDATE statement, and replace it with echo, (over the imploded variable), the selected IDs are showing up correctly.
sea otter 09-06-2006, 09:53 PM There might be a problem here:
if( count( $arr ) ){
foreach( $arr as $id )
$idstr = "'{$id}',";
}
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
In that
$idstr = "'{$id}';";
Needs a . concatenator character, and should be initialized:
if( count( $arr ) )
{
$idstr = '';
foreach( $arr as $id )
$idstr .= "'{$id}',";
}
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
That said, we can shorten all the code in the above block to:
$idstr = implode(',',$arr);
horizon 09-06-2006, 09:57 PM That said, we can shorten all the code in the above block to:
Yes. That's what I told myself the first time. Althought, the action is deleting more than the selected values. For instance, from the way you posted above, (if we replace all of it with implode as a simplification), if you select 1 ID - it will delete two of them (and one left (supposing you have three IDs in the field). If you select 2 of them, it will delete all of them. That's what I can't quite understand ...
Mech1 09-06-2006, 10:19 PM Some thing you could try is put a line in like echo("My query is: $sql"); just before your query is sent to mysql or some where it will be printed on screen. Then copy that and log in to mysql on the command line and past it in direct query and see what returns. It helps to know if what you think you ar sending is what you think it is.
Saeven 09-07-2006, 01:48 AM Good eye seaotter, serves me for typing code on my pda. You are correct. The original code block:
if( $row['user_id'] && count( $user_ids ) ){
$idstr = "";
foreach( $user_ids as $id )
$idstr = "'{$id}',";
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
//...
should be changed to:
if( $row['user_id'] && count( $user_ids ) ){
$idstr = "";
foreach( $user_ids as $id )
$idstr .= "'{$id}',";
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
This writ, that wouldn't have invalidated the SQL, it would have simply used only the last ID in the IN ( ) clause.
Good eye again though - thanks for that correction.
Horizon:
However, it has almost been three pages - instructed from the first post on what I was trying to accomplish but, unfortunitely, without success so far. Maybe if you posted that php page everyone preceding and including myself have requested, you would get an answer. Til you do, I desist! :)
horizon 09-07-2006, 06:25 AM if( $row['user_id'] && count( $user_ids ) ){
$idstr = "";
foreach( $user_ids as $id )
$idstr .= "'{$id}',";
$idstr = substr( $idstr, 0, strlen( $idstr ) -1 );
I will try that little dot addon later today and keep you posted.
However, wouldn't this line need to be changed into:
$idstr .= substr( $idstr, 0, strlen( $idstr ) -1 );
too ? ;)
2detailed 09-07-2006, 06:32 AM I'll hop back in here really quick. From the knowledge I have gained, it appears that you are storing multiple id's in a string, that is pulled from a mysql database, correct me if I am wrong? This is not a coding issue, it is a design issue, as far as the database goes, I would restructure the database, so each row has it's own controller id.
horizon 09-07-2006, 08:58 AM - it appears that you are storing multiple id's in a string, that is pulled from a mysql database, correct me if I am wrong?
Yes. Correct. This is what has been demonstrated since the first post.
- This is not a coding issue, it is a design issue, as far as the database goes, I would restructure the database, so each row has it's own controller id.
This is what I'm trying to avoid actually. I'd like to create multiple IDs through each ID rows and gain them once required.
P.S: Sorry for the quotes, I'm not actually at my computer and this keyboard is french so it looks kind of bad I know. ;)
2detailed 09-07-2006, 09:03 AM What reasoning do you have to do it like this? This is bad design, for various reasons.
horizon 09-07-2006, 09:55 AM I'm still wondering some topics contains some 'whys' on it. The reason that needs to be done is because of what I'm looking for to accomplish. Simple as that. ;)
horizon 09-07-2006, 06:55 PM I have just tried the latest corrections. The good news is, the foreach error is no longer showing up. The bad bews is, it's not updating the fields at all (or may be it does), the array remains the same in the targeted row and the HTML form is redirecting without affecting the rows.
maxymizer 09-07-2006, 08:10 PM You are trying to accomplish your task by using the wrong logic and wrong design. Since you don't like to be criticised, what's the point in asking for help?
You could have posted your database schema which would help others to help you. And your topic wouldn't expand to 3 pages because you are unable to form a string from an array.
Just a friendly criticism, no hard feelings.
horizon 09-08-2006, 08:27 AM You could have posted your database (http://www.webhostingtalk.com/showthread.php?t=544208&page=4#) schema which would help others to help you. And your topic wouldn't expand to 3 pages because you are unable to form a string from an array.
That's a good point of vue though. This isn't a critism but a more common sence solution ...
I guess it just didn't came to mind. Sorry about that. Next time, I will post my database schema. It is, indeed, more easier to understand. :)
sasha 09-08-2006, 09:06 AM Heh, I went through 4 pages and I am still not sure what are you trying to accomplish. It would be good idea to post:
1. HTML form where checkboxes are being checked
2. php code handling that
3. table structure
4. sample data for couple rows you are trying to update
5. echo $query to see what the actual query is
I will not go into design issue.
You are approaching this problem in a wrong way. First thing you should do is manually construct actual mysql query that will update sample row and see if that will work on it's own. Once you have the query working it should be simple thing to have your PHP construct it dynamically.
horizon 09-08-2006, 09:23 AM 1. HTML form where checkboxes are being checked
2. php code handling that
3. table structure
4. sample data (http://www.webhostingtalk.com/showthread.php?t=544208&page=4#) for couple rows you are trying to update
5. echo $query to see what the actual query is
1. Not required, for this case, since no. 5 does return the selected values.
2. Already did. Which means, you must of missed a couple posts.
3. Yes, I'm currently making the preparations on this.
4. Already did.
5. Already did (from my end, as explained from no. 1 and it does return the selected values).
First thing you should do is manually construct actual mysql query that will update sample row and see if that will work on it's own. Once you have the query working it should be simple thing to have your PHP construct it dynamically.
That is the whole point of this topic actually (as mentionned since my first post). When I try to, either, delete / update the targeted row, there are, either, different effects or no effect at all (as mentionned from one of my previous posts above).
;)
sea otter 09-08-2006, 09:24 AM Heh, I went through 4 pages and I am still not sure what are you trying to accomplish.
(shhhh. don't tell anyone. I still don't get it either! :confused: my only post was to point out a syntax problem.)
horizon 09-08-2006, 09:27 AM my only post was to point out a syntax problem
Hum ... nice try. Althought, the pages keeps increasing unfortunitely. ;)
sea otter 09-08-2006, 09:38 AM Well, I too eagerly await a solution :popcorn:
horizon 09-08-2006, 11:31 AM Great. When someone will post it technicly, I sure will be happy to try it out. :)
maxymizer 09-08-2006, 12:35 PM Post the schema of your entire table. I am looking at the posts and all I see is running arround in circle with creating a string from an array..not to mention that there are some illogical things in your code.
I don't even understand why are you setting user_id to an empty value instead of deleting the entire row.
horizon 09-08-2006, 01:25 PM I don't even understand why are you setting user_id to an empty value instead of deleting the entire row.
In that case, you did not understood the first post, since there's nothing mentionning about deleting the entire row. On the contrary, I wish to keep it.
maxymizer 09-08-2006, 02:16 PM In that case, you did not understood the first post, since there's nothing mentionning about deleting the entire row. On the contrary, I wish to keep it.
I didn't understand it because it's unclear. First of all, you are using word "apposition" which, in this particular case, has no meaning.
Second, you still didn't post the schema of your table.
And what's confusing at the most is what you're trying to achieve. Now, for the third time - if you wish to get assistance that will be of use to you, please post the schema of your table and explain what's the task you're trying to accomplish (not from programming point of view).
horizon 09-08-2006, 08:50 PM Here's the schema from the attachment link below.
Now, if you take a look at the user_id row, you will see many numbers in the same box. What I'm trying to do, as explained already from the first post, is to clear out, let's say - 2,4 (from the checkboxes from the HTML form) so that, only, 1,3,5,6 would remain in the box.
How could this be accomplish (without critism please) ?
So far, like I said, everything's working great for echoing the right values that has been selected. It's only when I wish to foreach it + use the SQL update statement - it fails.
maxymizer 09-08-2006, 11:14 PM This is as I thought, you're storing user_id's into a single field which makes things troublesome (as it's a varchar/char instead of an integer/float). You should store single user_id (as an integer) with single main_field in conjunction and create x user_id entries for each main_field (or whichever key of the table should act as primary, that's on you to know).
Following image should help understand what I mean.
10073
If that were your database design (bear in mind that user_id must be an integer with the design I'm proposing), you can safely use SQL query you were using in your fist post.
MySQL's IN() does not work as expected when you operate on varchars.
Doing what you want with your current db design can also be accomplished, but the price payed will be performance when your table gets big. If you decide to stay with your current system, you have to modify your MySQL query and instead of IN() use LIKE to match rows with similar occurences.
Code taken from your post (just modified SQL):
$sql_update = "
UPDATE table
SET user_id = '".$user_id_field."'
WHERE user_id LIKE %". $user_ids ."% AND id = ".$_SESSION['user_id'];
Of course this query is inaccurate and slow and more PHP processing should be involved to correctly target all rows. I strongly advise to change your db layout as I proposed.
inimino 09-09-2006, 04:54 AM Based on what you have in post #9, try this:
$remaining_array = array_diff($top_user_id_array,$user_id);
$remaining_string = implode(',',$remaining_array);
$sql_update = "UPDATE table SET user_id = '$remaining_string' WHERE id = '" . $_SESSION['user_id'] . "';"
$result = mysql_query($sql_update);
horizon 09-09-2006, 06:55 AM $remaining_array = array_diff($top_user_id_array,$user_id);
$remaining_string = implode(',',$remaining_array);
$sql_update = "UPDATE table SET user_id = '$remaining_string' WHERE id = '" . $_SESSION['user_id'] . "';"
$result = mysql_query($sql_update);
Sorry inimino. I tried it but, even when I echo the output, it does not display. However, if you have other solutions, based on this problem, I will be happy to try it on.
@maximizer:
$sql_update = "
UPDATE table
SET user_id = '".$user_id_field."'
WHERE user_id LIKE %". $user_ids ."% AND id = ".$_SESSION['user_id'];
should be changed to:
$sql_update = "
UPDATE table
SET user_id = '".$user_id_field."'
WHERE user_id LIKE '%". $user_ids ."%' AND id = ".$_SESSION['user_id'];
Otherwise, I will receive an SQL error syntax server message. ;)
Althought, unfortinutely, it results the same way I posted (once) on this topic:
- Supposing you have three IDs on your HTML form list, and wish to delete one of them, two IDs will be deleted rather than the selected one. Then, the last one remains. I cannot get rid of it. When I try to delete the last one, the action simply forwards to itself as the last ID number remains there as it is.
Any other solution ?
inimino 09-09-2006, 07:02 AM Sorry inimino. I tried it but, even when I echo the output, it does not display. However, if you have other solutions, based on this problem, I will be happy to try it on.
What, specifically, do you mean by "echo the output"? And what error are you receiving, or in what way is the code not doing what you expect? The code I suggested was to point you in the right direction, you may still need to do a little thinking to make it work. Please let me know what you tried.
horizon 09-09-2006, 07:02 AM the action simply forwards to itself as the last ID number remains there as it is
Continuing on what I said there. It might not be entirely true. It could also forward to the right action but cannot update the last field - period. Any other solutions on this would be greatly appreciated. ;)
horizon 09-09-2006, 07:04 AM What, specifically, do you mean by "echo the output"? And what error are you receiving, or in what way is the code not doing what you expect? The code I suggested was to point you in the right direction, you may still need to do a little thinking to make it work. Please let me know what you tried.
I tried exacly what you suggested. Althought, when the form gets posted, the IDs does not display under the echo command. It simply reforwards to the form itself. However, when I try Maximizer's inputs, it does executes the action but incorrectly. Which is why, other solutions would be amended. ;)
inimino 09-09-2006, 07:09 AM My suggestion was a block of code to be integrated in what you had in post #9. Now for me to have some idea of why it didn't work, I need to see how you integrated it with your existing code. Saying that you tried "exactly what I suggested" does not give me this information, nor does it answer my question of what exactly you are echoing. Please post the entire PHP page you tried. Posting your HTML form would also be extremely helpful.
horizon 09-09-2006, 07:14 AM what exactly you are echoing
Yes, sorry. I tried to echo the $remaining_string and it does not display anything. It simply reforwards to the form after going to that action. As for the $remaining_array, it displays the 'Array' word (as we already know).
When I apply the action, after - of course - removing the echo output and replace the SQL Update statement, the SQL Update statement just ... doesn't do anything. It doesn't update at all (or perhaps it does but simply re-integrates the same IDs inside which I can't be certain about).
inimino 09-09-2006, 09:03 AM What is the output of var_dump($top_user_id_array) and var_dump($user_id).
Also, I'm not sure what you mean by 'reforwards to the form after going to that action'. I haven't seen anything in the code you've posted so far that helps me interpret this remark.
Again, if you expect anyone to be able to help you, I would strongly suggest posting the HTML code of the form that you are trying to process. I don't understand why you haven't already done this as several people have asked for it and it would certainly help.
horizon 09-09-2006, 09:11 AM I don't understand why you haven't already done this as several people have asked for it and it would certainly help.
The HTML form is parsed from PHP. It would be useless to look at it, since it would require numerous PHP quotes under this forum in order to be entirely posted. As said before, the HTML form itself works at 100%. The only thing that needs to be resolved is the targetted action where the HTML form is being straightly posted. I hope you understand my point of vue.
As for the var_dump, I will try this out now and keep you updated . . .
horizon 09-09-2006, 09:17 AM Ok, I have just tried the var_dump command. Interesting response:
NULL array(2) { [0]=> string(1) "2" [1]=> string(1) "4" }
Any idea on what this means ? ;)
All I can understand on this line is the '2' and '4'.
inimino 09-09-2006, 09:28 AM The HTML form is parsed from PHP.
It doesn't matter how the HTML is generated, what matters is what the HTML itself says. This would give the experts here a better and more unambiguous idea of the semantics of your POSTed form data than all the English prose so far posted in this thread has done.
Since all we need is the HTML form, you don't need to worry about quoting the PHP. Just view the form in your browser, save the source, and cut and paste us the form. Simple as that.
inimino 09-09-2006, 09:34 AM NULL array(2) { [0]=> string(1) "2" [1]=> string(1) "4" }
Any idea on what this means ? ;)
All I can understand on this line is the '2' and '4'.
Yes, now we are getting somewhere. ;)
This means that one of your variables is NULL, and other is an array containing the string values "2" and "4". Presumably, 2 and 4 are the numbers you wish to delete from the list, no?
If so, you need to figure out why the first variable is NULL and you will be well on your way to correctly integrating my example and making your code work. Take a look at $top_user_id_array in your code, and find out where it is assigned. Based on your original post #9, I assumed it would contain an array of the numbers drawn from the current field in the database, but perhaps it does not. This is why I asked to see the complete PHP code you are now using.
horizon 09-09-2006, 09:35 AM Here:
<form method="post" action="myform.php">
<input type="hidden" name="action" value="send_form">
<input type="hidden" name="id" value="X">
<input type="checkbox" name="user_id[]">
<input type="submit" name="submit" value="Delete"> <input type="reset" name="reset" value="Reset">
</form>
Note: The 'X' has been replaced from the real ID value.
horizon 09-09-2006, 09:37 AM Yes, now we are getting somewhere.
Finally. :)
Presumably, 2 and 4 are the numbers you wish to delete from the list, no?
Yes. That is correct. I swear to 'always' use this command in the future for debugging (since I didn't even know what var_dump was useful for before now). ;)
If so, you need to figure out why the first variable is NULL and you will be well on your way to correctly integrating my example and making your code work.
So, are you saying this must be pointed to the primary key field rather than the user_id field ?
inimino 09-09-2006, 09:42 AM No, I am saying it should not be NULL and you need to figure out why it is and what it should be.
Take a look at $top_user_id_array in your code, and find out where it is assigned. Based on your original post #9, I assumed it would contain an array of the numbers drawn from the current field in the database, but perhaps it does not. This is why I asked to see the complete PHP code you are now using.
If you can understand what the array_diff() function does, and what the two arguments are expected to be, my example will suddenly make sense to you.
inimino 09-09-2006, 09:48 AM I swear to 'always' use this command in the future for debugging (since I didn't even know what var_dump was useful for before now). ;)
That alone will be worth the whole thread to you. :)
Now show us the rest of the PHP you are currently trying and we can most likely wrap this up.
horizon 09-09-2006, 09:57 AM if ($action == "send_form") {
if (isset($HTTP_POST_VARS['user_id'])) {
$user_id = (isset($HTTP_POST_VARS['user_id'])) ? $HTTP_POST_VARS['user_id'] : NULL;
} else {
$user_id = NULL;
}
if (!is_array($user_id)) {
die ('No permission.');
} elseif (is_array($user_id)) {
$date = date("Y-m-d");
$time = date("H:i:s");
$user_ids = implode(",", $user_id);
$user_ids_array = explode(",", $user_ids);
$remaining_array = array_diff($user_ids_array, $user_id);
$remaining_string = implode(",", $remaining_array);
/*var_dump($user_ids_array)."<br />";
var_dump($user_id);*/
$sql_update = "
UPDATE table
SET user_id = '".$remaining_string."'
WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql_update);
}
if ($result) {
header("Location: myform.php");
}
}
inimino 09-09-2006, 10:19 AM OK, the trouble here is that my original code snippet was based on your post #9 where you were querying the database to get the current list of numbers, and then updating it. In post #77, your code only updates the database, but never finds out what the current list of numbers is, so it's not going to do what you want.
Bringing back in a little bit of your original post #9 gives the following, which is more or less what you want. The important thing is not that this code works, but that you understand what it is doing. Then you know how to debug it if it isn't doing what you expect.
if ($action == "send_form") {
if (isset($HTTP_POST_VARS[URL_USER_ID])) {
$user_id = (isset($HTTP_POST_VARS[URL_USER_ID])) ? $HTTP_POST_VARS[URL_USER_ID] : NULL;
} else {
$user_id = NULL;
}
if (!is_array($user_id)) {
die ('No permission.');
} elseif (is_array($user_id)) {
$date = date("Y-m-d");
$time = date("H:i:s");
$user_ids = implode(",", $user_id);
$sql = "SELECT user_id FROM table WHERE id = '" . $_SESSION['user_id'] . "'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result))
$user_id_field = $row['user_id'];
$current_user_ids = explode(",", $user_id_field);
$remaining_array = array_diff($current_user_ids, $user_id);
$remaining_string = implode(",", $remaining_array);
/*var_dump($user_ids_array)."<br />";
var_dump($user_id);*/
$sql_update = "
UPDATE table
SET user_id = '".$remaining_string."'
WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql_update);
}
if ($result) {
//header("Location: myform.php"); //comment this out until you get the code you already have to work.
}
}
horizon 09-09-2006, 10:31 AM Ok. Just tried your version and same results. It returns to it's original page after updating nothing (or perhaps it does update but keeps the exact same readings - can't say).
Althought, this time, I have re-used the var_dump and here it is:
NULL array(2) { [0]=> string(2) "on" [1]=> string(2) "on" }
It's becoming hopeless. :(
inimino 09-09-2006, 10:51 AM OK, but the most critical line of my post was this:
The important thing is not that this code works, but that you understand what it is doing.
Do you understand what the code I suggested is supposed to do, and how that's the same as what you are trying to do? If not, ask questions. Perhaps I misunderstood what exactly you are trying to do, or perhaps you didn't fully understand the code I suggested.
Next, break the problem down into manageable chunks. Instead of trying to make everything work at once, just try to do this: create two arrays, $current_user_ids and $user_ids_to_delete. Put the values from the current row in the database into $current_user_ids, and the POST values into $user_ids_to_delete. You've had both of these parts working in the past, in other parts of your code. Use var_dump to figure it out.
Currently it looks like there is a problem with the way you are interpreting the form data, and perhas you var_dumped the wrong variable in the case of the first NULL, else your SQL query is failing.
Try to understand carefully what your code is doing, and take a break if you are feeling frustrated. Debugging is an acquired taste, and the less experience you have with it, the tougher it is.
I will be otherwise occupied for the next 12-24 hours but sometime after that I will try to stop by this thread again. Perhaps you can solve this in the meantime.
horizon 09-09-2006, 10:58 AM Do you understand what the code I suggested is supposed to do, and how that's the same as what you are trying to do? If not, ask questions. Perhaps I misunderstood what exactly you are trying to do, or perhaps you didn't fully understand the code I suggested.
Yes, at least I understood it. I coded something similar before creating this topic but yours was more expanded. It appeared that some lines were missing comparing to your version but still results the same though.
just try to do this: create two arrays, $current_user_ids and $user_ids_to_delete.
No sorry. This would be beside what I'd be looking for to do. I'm only looking for to do this instantly - all at once. ;)
Currently it looks like there is a problem with the way you are interpreting the form data, and perhas you var_dumped the wrong variable in the case of the first NULL, else your SQL query is failing.
Unfortunitely, I cannot see where NULL is coming from. However, what I can say is that the form looks pretty fine since each values are being captured properly. What's only missing is the proper way to call the SQL server properly and make the changes the right way. Otherwise, all seem to work fine (except for that NULL).
inimino 09-09-2006, 11:08 AM No sorry. This would be beside what I'd be looking for to do. I'm only looking for to do this instantly - all at once. ;)
I can't tell if you are being sarcastic, or if you misunderstood me? I am referring to the debugging process, not the code itself. Since it is already 82 posts in this thread without working code, I would say you must admit that your process of writing this code will not be instantaneous.
Unfortunitely, I cannot see where NULL is coming from. However, what I can say is that the form looks pretty fine since each values are being captured properly. What's only missing is the proper way to call the SQL server properly and make the changes the right way. Otherwise, all seem to work fine (except for that NULL).
That is a pretty big "except". Another big "except" is that you have an array of "on" and "on" rather than two numbers. This is quite different from the previous var_dump() output you posted. This is my last post in this thread for today, good luck.
horizon 09-09-2006, 12:06 PM you must admit that your process of writing this code will not be instantaneous.
Couldn't agree more there. I can't even remember the date this topic was ever created. Meaning - too long to get this issue resolved I might add.
horizon 09-09-2006, 12:14 PM IT WORKS !!!!!!! :)
@inimino:
Thanks very much for your help. Your code responds perfectly well from the targeted action. All is deleting for each IDs from the same row !!! :)
This is quite different from the previous var_dump() output you posted.
Didn't even noticed it was different. Which is why, I took a look at the HTML form again, since it was obvious the mistake was there. I forgot to add the value content with the user_id (but only after you posted your corrections) since I wanted to test something but forgot to replace the value content after the test was done. :)
Meaning,
<input type="checkbox" name="user_id[]">
should read :
<input type="checkbox" name="user_id[]" value="<?php echo $_SESSION['other_id']; ?>">
I can FINALLY rest !!! :cool: - Thanks again for your patience and kind help !
inimino 09-09-2006, 12:51 PM Great! Congratulations on finding a solution, I am glad I could help.
horizon 09-09-2006, 06:35 PM I guess I spoke a little too fast. Before I left my computer, I made one last test. Everything was fine. Althought, when I went back, the same behavior came back - two fields deleted for one selection for an unknown reason. It has changed behavior without knowing why ...
Any inputs on why it does so ? I haven't modified scratch since I last reported here . . .
maxymizer 09-09-2006, 07:47 PM A bit offtopic: horizon, did you read posts that referred to disfunctional database design and possibilities of innacurate row affection if you were to stay with your current db design or you just looked at posts with allready finished codes?
I'd like to know since it seems like a waste of time trying to explain the importance of proper db design if you're not interrested.
Edit: you are also eager to fix syntax errors of code(s) I provided, but it seems you didn't even try them out, nor did you fully understand what I was reffering to in my post. I'd like to know your standing on this, since this is the second thread you've made and you're again dealing with trivial problem and the thread has expanded to 5 pages due to your disinterrest in actually reading, understanding and giving feedback to people who are putting effort into helping you.
horizon 09-09-2006, 08:31 PM @maxymizer:
I totally beg to differ on all your last sentense. The reason why your solution was put aside, even though it was tried out, inimino did post an alternative solution which, first, responded to my needs. Since, I thought it would of remained a stable solution but would seem to have encountered, as mentionned from my last post, some unknown issues along the process. Hopefully, alternative solutions will be posted since I'm not discarding the fact that all of you are adding your inputs into this topic in order justify the best common solution to resolve this problem.
With that all said, your solutions has not been rejected, as you believe it was from above, but simply reconsidered for alternative solutions, since your suggestions is not quite the solution I'm currently looking for and I have already mentionned it before. It is true to say that more than several posts under topics might be unexpected but, no matter which mount of posts a topic might have, it is always important to follow each posts in order to understand the topic creator's objective.
Finally, I'm only considering the best solution to what I seek, like all other requesters on this forum. Meaning, even if you believe you're posting the best inputs, doesn't necessary means that the requester wishes to accept your recommendation directly. Decisions has to be considered first as evaluations needs to be made for each posted codes on this topic.
In the mean time, I believe it is quite the case here - to state that you aren't the only one recommending strategies in order to finalize this subject.
In other words, even if your inputs are still appreciated, it would be also helpful if you could recommend other subjects than single IDs from each rows, since I know my solution is typically possible to be achieved as I intend to maintain that objective. To be honnest, even if you post your inputs, it doesn't mean that the requester will use it - not because it might be a bad input but simply because it isn't the kind of answer she / he expecting for.
Rather than arguing longer over this, I'd rather wish to wait for inimino's inputs on this. Of course, if no inputs has been posted for a while, it would still be great to receive answers to what I'm trying to accomplish - on the right track. ;)
maxymizer 09-09-2006, 09:16 PM You are jumping to conclusions. I never stated that my solution was the best and the only one, as you have concluded.
I know what's your objective but you are just too stubborn to read + understand. I could have argumented the solution I proposed by explaning what normal forms are and why is it necessary and only right to use a lookup table the way I told you, since you are using the RDBMS in the wrong way and your software is misfiring and targeting wrong rows. On top of that, it's also slow (when it reaches a big row count your query will execute for a long time).
It's just your attitude that's making me insulted. I am putting my effort and spending my time explaining the basics of good database design to you, who didin't even try to ASK why this system and not the one you tried / are trying to use.
In the end, if you believe your approach to database design is within the aspect of good (proper) db design - why are you even trying to get answers from more experienced people?
Finally, I'm only considering the best solution to what I seek
I beg to differ. You are not even trying to understand anything, just to get done codes to accomplish your task which can be seen troughout this topic.
That puts you in a different position - you're not a coder in the process of learning as you don't enquire about anything, you are just a person who wants to get premade codes without paying the price for the job.
This is the first time I am actually insulted by someone who I tried to help to. You are inexperienced coder with a bad attitude and frankly, I suggest that you start reading and solving problems on your own. It's a trivial problem, your approach is wrong and start by reading up on what's database normalization, what are arrays and what are strings as you lack knowledge in those fields.
horizon 09-09-2006, 09:26 PM No insults was intended. What's been said was simply about personal choices that I would rather make rather than reading multiples choices of yours which suggest to use 1 IDs per rows. Again, that is not to be considered. Sorry.
I will wait for Inimino's codings since it seem to respond pretty well as I'm sure these last encountered issues were simply slight codings mistake which could be easily arranged.
Thanks again for your concern maxymizer.
2detailed 09-10-2006, 07:01 AM Wow, is all I have to say, well, I'm glad I stepped out a while ago, anyways best of luck Horizon, but next time, come here with your ears open and ready to listen, we only are trying to give you tested and proven methods, and why not to do this, and why to do this, and so on and so forth, why? Because we have been there, we have done 'beginner' coding, everyone is a beginner, and the only way you will get better is by reading, studying, listening, and keep on writing code...
Anyways best of wishes to everyone, good luck finding your solution.
P.S. wow, you guys have patience.... 90 posts in, wow....
horizon 09-10-2006, 07:34 AM Could you please stop posting your opinions ? It will only increase postings on this topic and this is NOT what I intend to receive. All I'm looking forward to read is the right technical answer to resolve this problem - period. It used to work and now it doesn't. It should be very easy to understand and hope to fix this issue pretty soon.
maxymizer 09-10-2006, 10:27 AM Could you please stop posting your opinions ?
No.
All I'm looking forward to read is the right technical answer to resolve this problem - period.
You allready recieved more than enough "technical" solutions. It's your own fault you cannot implement anything, after 90 posts.
:rolleyes:
horizon 09-10-2006, 11:26 AM Your decision is totally respected. If you do not wish to post here and let someone totally qualified in order to resolve this issue, the choice is totally yours. :)
inimino 09-10-2006, 12:49 PM Although, when I went back, the same behavior came back - two fields deleted for one selection for an unknown reason. It has changed behavior without knowing why ...
I would echo the SQL statement you are generating and var_dump() the arrays as before and then go from there...
horizon 09-10-2006, 01:25 PM I'm totally sorry inimino. I have put the last var_dump results aside but forgot to post it to you. I will do so this afternoon. :)
maxymizer 09-10-2006, 02:55 PM Your decision is totally respected. If you do not wish to post here and let someone totally qualified in order to resolve this issue, the choice is totally yours. :)
I am starting to develop telekinetic powers just in order to help you with the issue. Please, allow a few days until I evolve to the level on which we can communicate. I see you do refuse to read and understand what's been written, so we have to take another course in order to get your "issue" resolved.
horizon 09-10-2006, 03:30 PM @inimino:
I found it !!! I have reput the var_dump function and found a very slight issue. It was so small that I couldn't see it instantly. :)
Thanks for your outstanding assistance. Everything's in order now !! :cool:
inimino 09-10-2006, 03:59 PM Great! :)
|