sql delete from foreach function

Discussion in 'PHP' started by exoskeleton, Jun 30, 2012.

  1. #1
    hi guys.. masters... i have this problem deleting more than 1 record. my desired outcome should be:

    mysql_query("DELETE FROM employee WHERE emp_id IN (2,5)");

    2 and 5 are from foreach function ....

    is this possible?

    mysql_query("DELETE FROM employee WHERE emp_id IN (" .
    foreach ($values as $a)
    {
    $a;
    --$counter;
    if ($counter != 0)
    { . ',' . ; }
    else { .')'. ; }} );

    it wont work... im been working on this for 2 days... whew.. my brain aches... i just want to get the value from an array so i suppose to use foreach function for that and put it on the delete query but it wont work... please help... thank you in advance
     
    exoskeleton, Jun 30, 2012 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    $valuesStr = "('" . implode($values,"'") . "')";

    Something like this?
     
    EricBruggema, Jun 30, 2012 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    Eric has it right, you can't run procedural code (like foreach) as a function... which is what you are trying to do there. You need to build the string first...

    Though as also suggested, the IMPLODE function would mean you wouldn't need to waste time on foreach or the overhead of all those extra values... though his example makes no sense in context.

    
    mysql_query('
    	DELETE FROM employee
    	WHERE emp_id
    	IN ('.implode($values,',').')
    ');
    
    Code (markup):
    Should be all you need.

    Though to do it how you were trying, you'd have to run the foreach BEFORE the mysql_query function. Foreach is a procedural language construct -- you cannot use those as parameters to a procedure, you can only use functions for that.

    
    $queryValues='';
    foreach ($values as $a) {
    	$queryValues.=(
    		$queryValues=='' ? '' : ','
    	).$a;
    }
    
    mysql_query("
    	DELETE FROM employee
    	WHERE emp_id
    	IN ($queryValues)
    ");
    
    Code (markup):
    But really that's brute-forcing something PHP already has a function (implode) to handle for you.
     
    deathshadow, Jun 30, 2012 IP
  4. exoskeleton

    exoskeleton Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    sir eric and sir deathshadow... thank you very much.. il try to use implode now.. i never use it before thats why ive try different ways .. i know there must be other ways /function to do it much easier but i dont what is it.. thanks... il try now...
     
    exoskeleton, Jul 2, 2012 IP