Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hello Larry,

 

i work on your so interesting book.

I own the one issue and i "apprecie" your work.

 

In the extending partie first exemple,

"for placing html content Multiple categorie" ( page 407), i don't understand your words in the end of this article : 

"

 

And after the record is added to the pages table , you insert one record into page_categories…

 

But how create the Insert in the table "pages" with the addition of the Table pages_categorie ?

 

 

Thanks for advice or reference at one of your book where you explain this.

 

Cordially

Share this post


Link to post
Share on other sites

Hello Hartley,

 

yes i am trying this solution but i must do more test because my test code don't match now .

In the book it's for category but me i use this with Tag post.

 

Perhaps, if you know an exemple in line ?

 

so voilà an extract of my test code  with two query : 

	
../..
$insert = "INSERT INTO pages(cat_p_id,user_id,title,summary,ingredient,recipe,tips, status) VALUES (?,?,?,?,?,?,?,?)";
		$stmt = mysqli_prepare($dbc, $insert);
		
		mysqli_stmt_bind_param($stmt,'iiissssss',$_POST['category'],$_POST['user_id'],$st,$s,$i,$r,$ti);
		$allowed='<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li><blockquote>';
		$st= strip_tags($_POST['status']);
		$t= strip_tags($_POST['title']);
		$s= strip_tags($_POST['summary'], $allowed);
		$i= strip_tags($_POST['ingredient'], $allowed);
		$r= strip_tags($_POST['recipe'], $allowed);
		$ti= strip_tags($_POST['tips'], $allowed);
		
		mysqli_stmt_execute($stmt);
			if(mysqli_stmt_affected_rows($stmt) === 1){
			//mysqli_stmt_close($stmt);
			//echo'<div class="alert alert-success"><h3>Page ajoutée </h3></div>';
			}else{
			trigger_error('Systeme Error, Page non ajoutée.');
			}
		
		//ajouter lien vers page_tag	 / 
		$user_id = $_POST['user_id'];
		$tag = array();
		$getTag = "SELECT page_id  FROM pages WHERE user_id = $user_id";	
		
		$r = mysqli_query($dbc,$getTag);
		$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
		$page_id = $row['page_id'];
		foreach ($_POST['tag'] as $tag_id) {
			if(is_numeric($tag_id){
			$tags[] = "($page_id,$tag_id)";
			}
		}
	}
	
	if(!empty($tags)){
	$tags = implode(',', $tags);
		$noTags = false;
		}else{
			$noTags = true;
			}
	if(!$noTags){ //pages_tag => table de liaison
	$insertTags = "INSERT INTO  pages_tag(page_id,tag_id) VALUES $tags";
		mysqli_query($dbc, $insertTags);
		}
			
	}//errIf

Cordially

Share this post


Link to post
Share on other sites

I'm sorry I can't tell: are you still having problems with this or do you need help? And if the latter, please explain the exact problem (what's not working). Thanks!

Share this post


Link to post
Share on other sites

Hello Larry

in your chap 12, page 406-407, you propose an amelioration about multiple choice for Categorie.

so in the form you propose categorie[]

 

create the table page_categorie, ok

 

In the end of your proposition, i don't understand really how do the INSERT to the table's Page and after in the pages_categories.

 

I have not seen an example in one of your other books which otherwise?

 

thanks for an advice

Share this post


Link to post
Share on other sites

I'm pretty sure this is in one of my books, but I can't remember which. But if you name the form element categorie[], then $_POST['categorie'] will be an array. You can use a foreach loop to loop through the array, accessing every selected value. Then, within the foreach loop, you insert the category into the database. This is an excellent time to use prepared statements.

Share this post


Link to post
Share on other sites

Hello Larry,

 

in fine i really find the soluce, i think. It's difficult to test and you saw for the statement i do it when the code match.

 

So now  an error message said me

"An error occurred in script '/Applications/MAMP/htdocs/originalr/html/add_page.php' on line 124:

Array to string conversion"

 

so my code is

../..
if(isset($_POST['tag'])){
	$page_id = mysqli_stmt_insert_id($stmt);
	$tag = array();
				
				if(is_array($tag)){
					foreach ($tag as $tag_id) {
					$tag[] = "($page_id,$tag_id)";
					
					$tag= implode(',',$tag);
						echo('$tag'.$tag);
					}
				}else{
				echo'loupé coco';
				}
			
			
//test ok when tag is not an array
//$q = "INSERT INTO pages_tag(page_id, tag_id) VALUES ($page_id, $tag) ";

//test here with tag[] in form
	$q = "INSERT INTO pages_tag(page_id, tag_id) VALUES $tag";
			
	$retag = mysqli_query($dbc, $q);

i tested with   ... VALUES '$tag'";  idem error.

 

In the table "pages_tag"(the lookup table),

The result is :

page_id = 134 (it's well) and tag_id =0 (? the error);

so it's like (134,0).

normaly, i would like (134, 1), (134,5)  so depending the array tag[].

 

Where is the mistake ?

And when you descrive your soluce, it will be what you thought or another else?

 

Thanks for advice

Share this post


Link to post
Share on other sites

The error means that you're trying to use an array (variable) like a string, which you can't do.

Basically, you are probably thinking that some variable is a string, when actually, it's an array.

What's line 124 in your code?

Share this post


Link to post
Share on other sites

Hello Hartley,

 

thanks for response

 

the ligne 124 is

124  // $q = "INSERT INTO pages_tag(page_id, tag_id) VALUES $tag";

and normaly is the result of this


if(is_array($tag)){
                    foreach ($tag as $tag_id) {
                    $tag[] = "($page_id,$tag_id)";
                    
           
        $tag= implode(',',$tag);
                        echo('$tag'.$tag);
                    }
                }else{
                echo'loupé coco';
                }
            

is an array like   $tag = (page_id,tag_id);

 

bizzare non?

Share this post


Link to post
Share on other sites

Not bizarre. If line 124 is:

// $q = "INSERT INTO pages_tag(page_id, tag_id) VALUES $tag";

That's commented out, so it doesn't count. The next live line in what you provided is:

$q = "INSERT INTO pages_tag(page_id, tag_id) VALUES $tag"

And there you're using an array--$tag--as a string.

Share this post


Link to post
Share on other sites

Hello Larry 

 

sorry for the double slash, it was only to precise how i make the query.

 

$tag is normaly the result of 

if(is_array($tag)){
                    foreach ($tag as $tag_id) {
                    $tag[] = "($page_id,$tag_id)";
                    
           
        $tag= implode(',',$tag);
                        echo('$tag'.$tag);
                    }
                }else{
                echo'loupé coco';
                }

so $tag will be : 

 

$tag = ($page_id, $tag_id),  ($page_id_1, $tag_id_1), etc;

 

when in form, $tag isn't an array,

the result is fine. 

$q = "INSERT INTO pages_tag(page_id, tag_id) VALUES ($page_id, $tag) "; 

but when  if write  <  ../..   name="tag[]" /> , impossible to stock the data as an array.

 

that don't match

May i see how you write a foreach for this query ?

 

Thanks, 

Share this post


Link to post
Share on other sites

The problem is that you're using the variable $tag for two different purposes.

If $tag is an array, then you start to loop through it, and then you add another string element onto the end of the same $tag array, which is incorrect.

Furthermore, your approach to doing a multiinsert is incorrect. You have to build up the query string with multiple sets of parentheses.

 

For example:

$q = "INSERT INTO pages_tag (page_id, tag_id) VALUES";

if (is_array($tag)) {
  foreach ($tag as $tag_id) {
    $q .= " ($page_id, $tag_id)";
  }
} else {
  echo 'loupé coco';
}

$q .= ";";
echo $q; // This is the actual query string you want.

Please note that this code will leave you with an ill-formatted query string when $tag is not an array. You should account for that.

Share this post


Link to post
Share on other sites

Hello hartley

 

Sorry i' am a newdeveloper, and i think is not easy for me and also for you. I think to do something to difficult for me.

But i "persevere".

So  i think you code is right. In another way,  i test in simple "manière" without DataBase. it 's match  also like this.

But now in think that the problem is not here.

//test without table
$tag = array('classique', 'sans gluten', 'vegetarien',' vegetalien');
$page_id =('page');


foreach($tag as $tags){
	$r[]= "($page_id, $tags)";
	}
	
	echo '<br /> $r : ' .$r ;
	
	$rt .= implode(',', $r);
	echo '<br /> hello : ' .$rt;
	
	hello : (page, classique),(page, sans gluten),(page, vegetarien),(page, vegetalien)

In my form i do that, like the book with name="tag[]" for an array


 


echo'<div class="form-group';
	if(array_key_exists('tag', $add_page_errors)) echo ' has-error';
	echo '"><label for="tag" class="control-label">Le tag</label>
	<select name="tag[]" class="form-control" multiple="multiple" size ="7" ><option>Sélectionnez</option>';
		$qt="SELECT * FROM tag ORDER BY tag ASC";
		$rt=mysqli_query($dbc,$qt);
						while ($rowt=mysqli_fetch_array($rt, MYSQLI_NUM)) {
		$tag = array();
		$tag[] = $_POST['tag'];				
		echo "<option value=\"$rowt[0]\"";
				if(isset($_POST['tag']) && ($_POST['tag'] == $rowt[0]) ) echo 'selected = "selected"';
				echo ">$rowt[1]</option>\n";
				}//endwhile
				if(array_key_exists('tag', $add_page_errors)) echo'<span class="help-bloc">' .$add_page_errors['tag'].'</span>';
		echo '</select>';
		
		
		echo'</div>';
		print_r($tag);

When i submit all tag, i see that with "print_r($tag)"

But in code source any tags are :  selected = "selected"  why?

For the category i see the categorie selected. Perhaps the beginning of the soluce ?

<select name="tag[]" class="form-control" multiple="multiple" size ="7" ><option>Sélectionnez</option><option value="5">classique</option>
<option value="3">sans gluten</option>
<option value="4">sans lactose</option>
<option value="2">végétalien</option>
<option value="1">végétarien</option>
<span class="help-bloc">SVP, un tag au moins</span></select></div>Array
(
[0] => Array
(
[0] => 5
[1] => 3
[2] => 4
[3] => 2
[4] => 1
)

)
    

Thanks a lot. I work on it, i' am sure to find one day the soluce.

Share this post


Link to post
Share on other sites

laurent, there are actually a lot of issues with your code, but in general, it seems like you do not have a fundamental grasp of the difference between strings and arrays, and how they're used.

 

Please do me a favor and start at the beginning of Larry's book and any other basic PHP tutorials you can find to get the basics down.

Once you have the basics down, I think the rest will fall into place.

 

Thanks, and sorry if I hurt your feelings/pride at all.

Share this post


Link to post
Share on other sites

Hello Hartley,

 

The problem is in the sanitasize of the POST, is not  a number (INT) if $tag[] 

 

but an array so how make the if ?

if(filter_var($_POST['tag'], FILTER_VALIDATE_INT, array('min_range'=>1))){
			$tag = $_POST['tag'];
			}else{
			$add_page_errors['tag'] = 'SVP, un tag au moins sans image';
			}

Share this post


Link to post
Share on other sites

I'm not sure I understand your question, but it sounds like you're asking what to do when $_POST['tag'] is an array, and not a number.

 

If $_POST['tag'] is an array of numbers, then you can use a for loop or a foreach loop to loop through the array, and run the filter_var function on each of the elements in the array.

If the values are strings, then you can easily typecast the values to integers with (int).

 

That answer your question (assuming I even understood it correctly)?

Share this post


Link to post
Share on other sites
 
Hello Hartley

 

 

i though what the problem was in the  if( filter_var( ../..))

 

yes it was.

I test with only "if(!empty($_POST['tag']) ){ ../..  " and it's right the array is collected in Table pages_tag.

But What about security ?

I try with this

if(!empty($_POST['tag']) ){
			$tag = filter_var_array( $_POST['tag'], FILTER_SANITIZE_STRING);
			}else{
			$add_page_errors['tag'] = 'SVP, un tag ou plus';
			}

it's perhaps not the best solution, but looking around information i shall found the one.

 

For the $query i do that and that match:



$tag = array();
$tags='';
		if(isset($_POST['tag']))
		{
			$page_id = mysqli_stmt_insert_id($stmt);
				
					foreach ($_POST['tag'] as $tag_id) {
							if(is_numeric($tag_id)){
								$tag[] = "($page_id, $tag_id)";
							}//isNum		
						}//	postTag		
				$tags .= implode(',', $tag);
			
		//Base query : $q = "INSERT INTO pages_tag(page_id, tag_id) VALUES ($page_id, $tag) ";
				$q = "INSERT INTO pages_tag(page_id, tag_id) VALUES $tags ";
			
				$retag = mysqli_query($dbc, $q);
			
		}//end ifpostTag

Thanks for the advice, Cordialy

Share this post


Link to post
Share on other sites

laurent, I can't really give you any advice because I can't understand your question or your code.

Could you please rephrase your question?

Thanks.

  • Upvote 1

Share this post


Link to post
Share on other sites

Hello Hartley,

 

I wanted to thank you for the help to understand and solve my problem. 

Now i can add my query for  pages_tag to the DB. For me is right. 

In my precedent post "Posted 7/05/2014, 10:55 AM",

i explain with your help the solution i found .

 

thanks a lot and certainly at the next "problème" for a reflexion about coding. 

Cordially Hartley

Share this post


Link to post
Share on other sites

Hello Larry, Hartley,

 

 

suite of the multiple Category advice,

 

(ps. For me i use a "button checkbox" instead selector and "Tag" for Category)

 

 

The insert function is ok.

i worked on another part of my site and i come back to the  author admin.

 

 

 

For UPDATE information all is ok but only one field   don't match well : "Tag" .

 

 

Only 1 checkbox is checked on the form and this is the last one.

 

 

 

 in DB $tag = (végétalien, sans gluten, classique)

$tag = explode(',', $tag);
foreach ($tag as $tags) {
		switch ($tags) {
			case "végétarien":
			$tag_id = 1;
			break;

			case "végétalien":
			$tag_id = 2;
break;
			case "sans gluten":
			$tag_id = 3;
			break;

			case "sans lactose":
			$tag_id = 4;
			break;

			case "classique":
			$tag_id = 5;
			break;

			default:
			$tag_id = 0;
			break;
			}//switch

			
	echo( '<br /> tag : ' .$tags .' et tag_id : ' . $tag_id .'<br />');

// echo //

 

tag : végétalien et tag_id : 2

tag : sans gluten et tag_id : 3

tag : classique et tag_id : 5
 

the query is ok all tags are here and ok with BD

 

but Only one checkbox is checked on the form.

 

The FORM 

 <div class="checkbox form-control">
		<label for="tag" class="control-label">Tag</label>
		<?php 
		$qt="SELECT tag_id, tag FROM tag ORDER BY tag DESC";
		$r=mysqli_query($dbc,$qt);
			while ($row=mysqli_fetch_array($r, MYSQLI_ASSOC)) {?>
				<div class="checkbox <?php if(array_key_exists('tag', $update_page_errors)) echo ' has-error'; ?>">
	<label>
<input type="checkbox" name="tag[]" id="<?php echo $row['tag'] ?>" value="<?php echo $row['tag_id'] ?>"
<?php if(isset($tag) && ($tag_id == $row['tag_id'])) echo !empty('checked="checked"') ? 'checked="checked"' : '';?>><?php echo $row['tag'] ?>
					 	</label>
				</div>
		    <?php if(array_key_exists('tag', $update_page_errors)) echo'<span class="help-bloc">'.$update_page_errors['tag'].'</span>'; ?>
		    
			<?php } ?>
	</div>	   

an error on the html form?

 

Sometimes when we have only one and the last response with a loop, it's a problem in a loop ?

 

 

Some advices and thanks for reply

 

Merci d'avance pour une piste de recherche

Cordialement

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...