Jump to content

Clearing Array


kingnutter

Recommended Posts

I'm trying to use array_diff and my arrays are getting clogged up with previous entries.

 

What is the best way to clear $orig_genres, $new_genres and $missing_genres below, bearing in mind that I am still debugging a script and not yet able to run through to the end of it?

 

<?php
$orig_genres=array();

foreach (($_SESSION['tags']) as $single_genre)
{
$orig_genres[] = $single_genre;
}


unset($_SESSION['tags']);

// Create new_genres string

$new_genres = explode(",", $moj_genre);

echo "Original Genres: ";
print_r($orig_genres);
?><br><?php
echo "New Genres: ";
print_r($new_genres);
?><br><?php
$missing_genres=array_diff($orig_genres, $new_genres);
echo"Missing Genres: ";
print_r($missing_genres);

Link to comment
https://forums.phpfreaks.com/topic/174075-clearing-array/
Share on other sites

If you were to post an example that shows what data you have, what the expected results should be, and what result you are getting, someone could directly help you with what is wrong. For all we know your code is working correctly but there is something wrong with the data, such as white-space in part of it or letter-case differences...

Link to comment
https://forums.phpfreaks.com/topic/174075-clearing-array/#findComment-917620
Share on other sites

This is basically for an update page of a CMS, the field I am stuck with is the recalling (working ok) and amending / deleting (the problem) tags.

 

I am testing and testing, but as the arrays do not seem to be clearing it is getting more and more confusing. Along with all the JOINed table MySQL queries I'm trying to write, it's so hard to know how to isolate areas. I had thought of white-space errors as a print_r of arrays seems unecessarily spaced.

 

You asked for it, so here's the script. I am editing from about half way through, though as you rightly point out the problems may occur earlier. Apologies for length(!)

 

<?php
// Starting the session
session_start('tags');
session_start('username');

$username = ($_SESSION['username']);

if ($username !== 'username goes here')


{ 

header("Location: index.php");

}

?>

<html> 

<head></head> 

<body> 

<!-- standard page header --> 

<?php 

// includes 

include('conf.php'); 

// include('functions.php'); 

// form not yet submitted 

// display initial form with values pre-filled 

if (!$_POST['submit']) 

{ 

     // check for record ID 

     if ((!isset($_GET['id']) || trim($_GET['id']) == '')) 

     { 

         die('Missing record ID!'); 

     } 

    // open database connection 

    $connection = mysql_connect($host, $user, $pass)

or die ('Unable to connect!'); 

    // select database 

    mysql_select_db($db) or die ('Unable to select database!'); 

    // generate and execute query 

    $id = $_GET['id']; 

    $query = "SELECT moj_title, moj_issue, moj_summary FROM mojocd WHERE moj_id = '$id'";  

    $result = mysql_query($query)

or die ("Error in query: $query. " . mysql_error()); 

$query = "SELECT moj_date FROM mojocd WHERE moj_id = '$id'";

$result2 = mysql_query($query)

or die ("Error in query: $query. " . mysql_error()); 


$moj_date_string = mysql_result($result2, 0, 0);
$moj_date_exp = explode(' ', $moj_date_string);

$moj_date_exp = array_reverse($moj_date_exp);
$year = isset($moj_date_exp[0])?$moj_date_exp[0]:'';
$month = isset($moj_date_exp[1])?$moj_date_exp[1]:'';
$day = isset($moj_date_exp[2])?$moj_date_exp[2]:'';
// echo $year." ".$month." ".$day;

    // if a result is returned 

    if (mysql_num_rows($result) > 0) 

     { 

        // turn it into an object 

        $row = mysql_fetch_object($result); 

        // print form with values pre-filled 



?> 

<table cellspacing="5" cellpadding="5"> 
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> 
<input type="hidden" name="id"  value="<?php echo $id; ?>"> 


<!-- Create pre-valued field to edit title
<tr> 
    <td valign="top"><b><font size="-1">Edit Title</font></b></td> 
    <td> 
      <input size="50" maxlength="254" type="text" name="moj_title" 
value="<?php echo $row->moj_title; ?>"> 
    </td> 
</tr>

<tr>
<td valign="top"><b><font size="-1">Edit Date</font></b></td>
<td>
<?php 

// Make the months array:

$months = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

// Make the days and years arrays

$days = range (1, 31);
$years = range (2001, 2009);
$freq = "monthly";


if ($freq == "daily")

{	
// Make the days pull-down menu:
echo '<select name="day">';
foreach ($days as $value) 
if ($day == $value)
    { 
        echo "<option value=\"$day\" selected>$day</option>"; 
	} 
else
{
	echo "<option value=\"$value\">$value</option>\n";
	}
	echo '</select>';
}

// Make the months pull-down menu:

if (($freq == "daily") || ($freq == "monthly"))

{
echo '<select name="month">';
foreach ($months as $value) 
if ($month == $value)
	{
	echo "<option value=\"$month\" selected>$month</option>";
	}
else
	{
echo "<option value=\"$value\">$value</option>\n";
	}
echo '</select>';
}

// make the year pull-down menu:

if (($freq == "daily") || ($freq == "monthly") || ($freq == "yearly"))

{	
echo '<select name="year">';
foreach ($years as $value) 
if ($year == $value)
	{
	echo "<option value=\"$year\" selected>$year</option>";
	}
else
	{
	echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';
}

?>

</td>
</tr>
<tr> 

    <td valign="top"><b><font size="-1">Edit Issue Number</font></b></td> 

    <td> 

      <input size="5" maxlength="5" type="text" name="moj_issue" value="<?php echo $row->moj_issue; ?>">    </td> 

</tr> 

<tr> 

    <td><b><font size="-1">Edit Summary</font></b></td> 

    <td> 

      <textarea name="moj_summary" rows="8" cols="43"><?php echo $row->moj_summary; ?></textarea> 

    </td> 

</tr> 

<tr> 

    <td valign="top"><b><font size="-1">Edit Genre Tags</font></b><br><font size="-1">Separate with commas</font></td> 
<td>
<input size="45" max length="254" type="text" name="moj_genre" value="
<?php


$query="SELECT moj_genre FROM genres INNER JOIN genrelinkcd ON genres.genre_id=genrelinkcd.genre_id WHERE genrelinkcd.moj_id='$id'";
$result=mysql_query($query);



while($row = mysql_fetch_array($result))
{
echo "$row[0]".", ";
// $orig_genres[] =$row[0];
$_SESSION['tags'][]=$row[0];
}


?>	

">


</tr> 


<tr> 

    <td colspan=2> 

      <input type="Submit" name="submit" value="Update"> 

    </td> 

</tr> 

</form> 

</table> 

<?php 

    } 

    // no result returned 

    // print graceful error message 

    else 

    { 

        echo '<font size=-1>That instance could not be located in the database.</font>'; 

    } 

} 


else 

{ 

    // set up error list array 

    $errorList = array(); 

    $moj_title = $_POST['moj_title']; 

$moj_issue = $_POST['moj_issue'];

$moj_day = $_POST['day'];

$moj_month = $_POST['month'];

$moj_year = $_POST['year'];

    $moj_summary = $_POST['moj_summary']; 

$moj_genre = $_POST['moj_genre'];

    $moj_id = $_POST['id']; 


        
// Check for errors

if (trim($_POST['moj_title']) == '')
{
	$errorList[] = 'Invalid entry: Title';
}


if (trim($_POST['moj_issue']) == '')
{
	$errorList[] = 'Invalid entry
}

if (trim($_POST['moj_summary']) == '')
{
	$errorList[] = 'Invalid entry: Summary';
}

if (trim($_POST['moj_genre']) == '')
{
	$errorList[] = 'You must enter at least one genre tag';
}


if (trim($_POST['day']) == '' && ($freq == "daily"))
{
	$errorList[] = 'Invalid entry: Day of date';
	}

if (trim($_POST['month']) == '' && (($freq == "daily") || ($freq == "monthly")))
{
	$errorList[] = 'Invalid entry: Month of date';
	}		

if (trim($_POST['year']) == '' && ((($freq == "daily") || ($freq == "monthly") || ($freq == "yearly"))))
{
	$errorList[] = 'Invalid entry: Year of date';
	}		
    // if none found... 

    if (sizeof($errorList) == 0) 

    { 

        // open database connection 

        $connection = mysql_connect($host, $user, $pass)

or die ('Unable to connect!'); 

        // select database 

        mysql_select_db($db)

or die ('Unable to select database!'); 

// $date = "$moj_day"." "."$moj_month"." "."$moj_year";  



// if monthly turn $day into 01 and use $month and $year for $unixdate
// $day = '8';
// $month = 'February';
// $year = '1978';
$freq = 'monthly';

if ($freq == 'daily') 
{
$moj_date = "$moj_day"." "."$moj_month"." "."$moj_year";
}

if ($freq == 'monthly')
{
$moj_day = '1';
$moj_date = "$moj_month"." "."$moj_year";
}
// if yearly, turn $day into 01 and $month into 01 and use $year for $unixdate


if ($freq == 'yearly')
{
$moj_day = '1';
$moj_month = 'January';
$moj_date = "$moj_year";}


$dateforunix = "$moj_day-$moj_month-$moj_year + 1 hour";
$unixdate = strtotime($dateforunix);

// echo $dateforunix; ?><br><?php
// echo $unixdate; ?><br><?php
// echo $date;


// generate and execute query
$query = "UPDATE mojocd SET moj_title = '$moj_title', moj_date = '$moj_date', moj_issue = '$moj_issue', moj_summary = '$moj_summary', unix_timestamp = '$unixdate' WHERE moj_id = '$moj_id'";

$result = mysql_query($query)
or die ("Error in Query: $query. " . mysql_error());

//*** PROBLEMS START HERE! ***

// Return original genres from 'tags' SESSION
$orig_genres=array();

foreach (($_SESSION['tags']) as $single_genre)
{
$orig_genres[] = $single_genre;
}


unset($_SESSION['tags']);

// Create new_genres string

$new_genres = explode(",", $moj_genre);

// I've been "print_r"-ing here to check what's in the arrays

echo "Original Genres: ";
print_r($orig_genres);
?><br><?php
echo "New Genres: ";
print_r($new_genres);
?><br><?php
$missing_genres=array_diff($orig_genres, $new_genres);
echo"Missing Genres: ";
print_r($missing_genres);
$missing_genres = Array();
//now we have to count the occurances of each $missing_genre in genrelinkcd. If it is 1 it will no longer exist as a genretag and needs to be deleted from the table genres. Whatever the outcome, $missing_genre needs to be deleted where moj_id=$moj_id


foreach ($missing_genres as $row)
{
    // open database connection 

    $connection = mysql_connect($host, $user, $pass)

or die ('Unable to connect!'); 

    // select database 

    mysql_select_db($db) or die ('Unable to select database!'); 

$query="SELECT *
FROM genres g
INNER JOIN genrelinkcd gl 
ON g.genre_id = gl.genre_id
WHERE g.moj_genre = '$row'";

$result = mysql_query($query);

echo mysql_error();
$amount = mysql_num_rows($result);    

//Get amount as $amount

if ($amount == 1)
{

// If it is the only instance, delete the tag from the 'genres' table

$query="DELETE * FROM genres WHERE moj_genre='$row'";
$result = mysql_query($query) or die;

}

// Delete the genres that are now missing from genrelinkcd

// NB: Haven't got round to this and following queries properly yet

$query="DELETE * FROM genrelinkcd WHERE genrelinkcd.genre_id = (SELECT genre_id FROM genres WHERE moj_genre='$row') AND	genrelinkcd.moj_id='$id'";
$result = mysql_query($query) or die;
}


//establish which tags are new. Simply reverse the strings in array_diff!

$added_genres=array_diff($new_genres, $orig_genres);

foreach ($added_genres as $row)
{
$query="SELECT * FROM genres WHERE moj_genre='$row'";

$result = mysql_query($query);
$amount = mysql_num_rows($result);    

//Get amount as $amount

if ($amount == 0)
{

// If it does not already exist in genres, add it to genres

$query="INSERT INTO genres (moj_genre) VALUE ('$row')";
$result = mysql_query($query) or die;
}

// put a record in genrelinkcd whatever the result

$query="INSERT INTO genrelinkcd (genre_id, moj_id) VALUES (genres.genre_id WHERE genres.moj_genre = '$row'), '$id'";
$result = mysql_query($query) or die;

}
?> 
"


    </td> -->
<!--
<script language="JavaScript" type="text/JavaScript">

window.location.href = "list.php?id=<?php echo "$moj_id"."&happened=updated"; ?>";

</script>



<?php
    } 

    else 

    { 

        // errors occurred 

        // print as list 
	// THESE SHOULD HAPPEN AS A JS POP-UP OVER EDIT PAGE - EXPERIMENT!!!
        echo '<font size=-1>The following errors were encountered:'; 

        echo '<br>'; 

        echo '<ul>'; 

        for ($x=0; $x<sizeof($errorList); $x++) 

        { 

            echo "<li>$errorList[$x]"; 

        } 

        echo '</ul></font>'; 

    } 

} 

?> 


<!-- standard page footer --> 

</body> 

</html> 

Link to comment
https://forums.phpfreaks.com/topic/174075-clearing-array/#findComment-917701
Share on other sites

Here is an example of the result I am getting (using print_r for all the array strings):

 

Original Genres: Array ( [0] => Rock [1] => Punk [2] => New Wave [3] => Trash )

New Genres: Array ( [0] => Rock [1] => Punk [2] => New Wave [3] => Pop )

Missing Genres: Array ( [1] => Punk [2] => New Wave [3] => Trash )

 

"Trash" in Original Genres has been replaced by "Pop" in New Genres, thus I would expect Missing Genres to only contain "Trash".

Link to comment
https://forums.phpfreaks.com/topic/174075-clearing-array/#findComment-918339
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.