Problema con questo errore Error was: Undefined index: title linea 9

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Ricevo questo errore nel seguente codice che è collegato ad un'altro per i commenti se potreste darci un'occhiata e capire dove sbaglio perchè fino a che non metto il form per i commenti tutto funziona quando cerco di inviare un commento ad un determinato post mi da l'errore Error was: Undefined index: title line 9... Grazie pr l'aiuto.
ecco i due codici:
1)
PHP:
<?php
function Blog (Database $db, Request $request){
	$author ="";
	$title 	="";
	$article="";
	$msg_to_user="";
	if (isset($_POST['author'])) {
    $author = $_POST['author'];
	$title = $_POST['title']; //qui da l'errore quando premo send nel form dei commenti solo che nel form dei commenti non ho un titolo perchè non è bisogno 
	$article = $_POST['article'];
	$sql = "SELECT * FROM articles WHERE art_title='$title'";
	$result = $db->getData($sql);
	$numRows =0;
	foreach ($result as $row){
		$numRows++; 
	}
	if (!$author) {
		
		$msg_to_user = "<br /><br /><h4><font color='FF0000'>Please insert author!</font></h4>";
		
	}else if (!$title){
	
		$msg_to_user = "<br /><br /><h4><font color='FF0000'>Please insert title!</font></h4>";
		
	}else if (!$article) {
	
		$msg_to_user = "<br /><br /><h4><font color='FF0000'>Please insert article!</font></h4>";
		
	} else if ( $numRows > 0) {
		
		$msg_to_user = "<br /><br /><h4><font color='FF0000'>'$title' exist please choose a different one!.</font></h4>";
		
	} else {
		
		$sql = "INSERT INTO articles (art_author, art_title, art_articles, art_date) VALUES('$author','$title', '$article', now())";
		$db->query($sql);// !!!!!!IMPORTANT FOR RUN THE SQL!!!!!!!!!!!!!!!!
		//echo mysql_error();
		$msg_to_user = "<br /><br /><h4><font color='0066FF'>Thanks '$author', article posted.</font></	h4>";
		$author = "";
        $title = "";
        $article = "";
	}
} 
 	$out  = "<section class='blog'>";
	$out .= "<h1>share here your opinions and your comments on our blog</h1>";
	$out .="<fieldset class='blog_form'>";
	$action = "index.php?page=blog&amp;postState=new-article-posted";
	$out .= "<form action='$action' method='post' class='bl_form'>";
	$out .= "Author:<br>";
	$out .= "<input name='author' type='text' size='30' value='$author'><br>";
	$out .= "Title:<br>";
	$out .= "<input name='title' type='text' size='30' value='$title'><br>";
	$out .= "Article:<br>";
	$out .= "<textarea name='article' cols='40' rows='10' value='$article'></textarea><br>";
	$out .= "<input name='submit' type='submit' value='Send'>";
	$out .= "$msg_to_user";
	$out .= "</form>";
	$out .= "</fieldset>";
	$whichArticle = $request->get("show-article");
	if ($whichArticle) {
		$out .= "<div class='article_blg'>";
        $out .= showArticle($db, $whichArticle);//One article
        include_once 'views/comments_art.php'; //qui ho incluso i commenti senza questo tutto il resto funziona
		$out .= Comments_art($db, $whichArticle);//comments included here
		$out .= "</div>";
        
       
        } else {
        $out .= showAllTitles($db);//list of titles
    }

		return $out;
	}
	
	function showAllTitles(Database $db){
	
	$out  = "<div class='articles_blog'>";
	$out .= "<h1>ARTICLES</h1>";
	$out .= "<ul id='articles_bl'>";
	//Get all Articles from db and shows all titles
	$allArticle = getAllArticles($db);
	foreach ($allArticle as $row) {
    //Must take all rows and output list -> titles??
	$id = $row->get("art_id");
	$date = $row->get("art_date");
	$article = $row->get("art_title");
	$txt = $row->get("art_articles");
	$date = preg_replace('/^(.{4})-(.{2})-(.{2})$/','$3-$2-$1', $date);
    $href = "index.php?page=blog&amp;show-article=$article";
    $out .=	"<li>";
    $out .=	"<a href='$href'>$article</a>&nbsp&nbsp";
    $out .= "<em>$date</em>";
    $out .= "<p class='prev_art'>";
    $out .= preview($txt, 10, $href);
    //$out .= substr($txt, 0, 30);
    /*$preview = new Preview();
    $preview->makePreview("$article");
    $out .= "$preview";*/
    $out .= "</p>";
    $out .= "<a href='index.php?page=blog&amp;show-article=$article'>Read more</a>";
    $out .= "</li>";
    }
    $out .= "</ul>";
    $out .= "</div>";
    $out .= "</section>";
	return $out;
	}
	//Get from DB all Articles
	function getAllArticles(Database $db) {
	$sql = "SELECT * FROM articles ORDER BY art_date DESC";
	$db->query($sql);
    //$sql = "SELECT art_title FROM articles";
	$table = $db->getData($sql);
    return $table;   
    }
    
	function showArticle(Database $db, $whichArticle) {
	$data = getArticle($db, $whichArticle);
	$title = $data->get("art_title");
	$author = $data->get("art_author");
	$article = $data->get("art_articles");
	//$out  = "<div class='article_blg'>";	
	$out  = "<h1>Title:</h1><p>$title</p>";
	$out .= "<h2>Author:</h2><p>$author</p>";
	$out .= "<h3>Article:</h3><p>$article<br></p>";
    //$out .= "</div>";
	return $out;
	}
	
	function getArticle(Database $db, $articles) {
    $fname = $db->escapeString($articles);
    $sql = "SELECT art_title, art_articles, art_author FROM articles WHERE art_title = '$fname'";
    $db->query($sql);
    $data = $db->getData($sql);
    $row = $data->getAt(0);
    return $row;
}

function preview($txt, $long, $final) {

		return (count($words = explode(' ', $txt)) > $long) ? implode(' ', array_slice($words, 0, $long)) . $final : $txt;
		
}
per i commenti il seguente:
2)
PHP:
function Comments_art (Database $db, $article){
	
    $out = html("section")->attr("art_comments");
    
    $formData = new Request("post");
    $newCommentSubmitted = $formData->get("new-comment"); 
    if ( $newCommentSubmitted ) {
        
        insertComment( $db, $formData ); 
        $formData->clear();
    }
    $out->append( showForm($article) );
    $out->append( showComments( $db, $article) );
    
    return $out->asHTML();
}


function showComments (Database $db, $article) {
	$allComments = getComments( $db, $article ); 
    $ul = html("ul");
    foreach ( $allComments as $commentData ) {
        
        $author = $commentData->get("com_author");
        $comment = $commentData->get("com_text"); 
        $date = $commentData->get("com_date"); 
        $ul->append("<div id='comment_user'><p id=AuthorComment> $author</p><p id='comment_text'> $comment</p><p id='dateComment'> $date</p></div>");
    }
    return $ul; 
}

function getComments( Database $db, $article ) {
    $sql = "SELECT com_id, com_author, com_text, DATE_FORMAT (com_date,'%d %b %Y %H:%i') AS com_date FROM comments
            WHERE com_art = '$article' ORDER BY com_id DESC"; 
    return $db->getData($sql);
}

function showForm( $article ) {
    $action = "index.php?page=blog&show-article=$article&amp;com_art=$article";
    //$out = "<div id='guestbookForm'>";
    $form = html("form")->attr("id", "comment-form"); 
    $form->attr("action", $action)->attr("method", "post"); 
    $hidden = emptyTag("input")->attr("type", "hidden"); 
    $hidden->attr("name", "id")->attr("value", "$article"); 
    $form->append($hidden);
    $form->append(
        '<div class="commentForm">
		<h1>Comment the article</h1>
        <label class="com_author">Author:</label> 
        <input type="text" name="author" placeholder="author" class="com-author" /> 
        <textarea class="com_txt" name="new-comment" placeholder="Your comment here" ></textarea> 
        <input type="submit" value="Comment" class="post_B"/>
        </div>'
);
return $form;
}


function insertComment( Database $db, Request $formData ) {
    
    $id = $formData->get( "com_id" );
    $author = $formData->get( "com_author" );
    $comment = $formData->get( "com_text" );
    $sql = "INSERT INTO comments (com_author, com_text, com_art) 
            VALUES ( '$author', '$comment', '$id' )";
    $db->query( $sql ); 
   
}
 

flameseeker

Utente Attivo
27 Nov 2013
699
0
0
E' un pò disordinato il codice, ti suggerirei di fare un pò di pulizia rispettando le indentazioni.

In ogni caso, il tuo problema si verifica perché nel form dei commenti..
PHP:
$form->append(
        '<div class="commentForm">
        <h1>Comment the article</h1>
        <label class="com_author">Author:</label> 
        <input type="text" name="author" placeholder="author" class="com-author" /> 
        <textarea class="com_txt" name="new-comment" placeholder="Your comment here" ></textarea> 
        <input type="submit" value="Comment" class="post_B"/>
        </div>'
);
..stai inviando il dato dell'autore con name="author", di conseguenza quando lanci la funzione Blog..
PHP:
if (isset($_POST['author'])) {
    $author = $_POST['author'];
    $title = $_POST['title'];
..questo controllo viene superato e php ti chiede "title" che giustamente non hai.


Adesso, basandomi su ciò che leggo:
PHP:
$id = $formData->get( "com_id" );
$author = $formData->get( "com_author" );
$comment = $formData->get( "com_text" );
Dovresti impostare gli attributi name dei campi del form come è indicato qui, in più mi vien da supporre che il metodo get() della tua classe Request sia collegato al superglobale $_GET di php, mentre tu assegni il metodo post nella creazione del form
PHP:
$form->attr("action", $action)->attr("method", "post");


Se tutte le mie supposizioni sono corrette, per risolvere il problema dovrebbero bastare le seguenti modifiche:

. Nello script che ti genera il form, sostituendo i name dell'input nascosto e di quelli aggiunti con append()
PHP:
$hidden->attr("name", "com_id")->attr("value", "$article"); 
    $form->append($hidden);
    $form->append(
        '<div class="commentForm">
        <h1>Comment the article</h1>
        <label class="com_author">Author:</label> 
        <input type="text" name="com_author" placeholder="author" class="com-author" /> 
        <textarea class="com_txt" name="com_text" placeholder="Your comment here" ></textarea> 
        <input type="submit" value="Comment" class="post_B"/>
        </div>'
);

. Nello script di inserimento, cambiando il metodo da get a post
PHP:
$id = $formData->post( "com_id" );
$author = $formData->post( "com_author" );
$comment = $formData->post( "com_text" );
 

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Grazie dell'aiuto ho risolto l'errore. L'unica cosa il form non mi inserisce i dati nel db adesso. Cmq grazie mille e cerchero di fare più ordine nel mio codice :)
 

flameseeker

Utente Attivo
27 Nov 2013
699
0
0
Prova a visualizzare gli errori che ti ritorna il database, così vediamo di capire qual è il problema ;)
 

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Ciao grazie del consiglio. Ho provato a vedere gli errori con un echo mysql_error(); ma non mi ristituisce nessun errore. Mi puoi dire in che altro modo posso vedere se ci sono?.
Cmq mi restituisce solo il form senza fare pero l'inserimento dei dati nel db. Molto strana questa cosa ho cercato di fare come mi hanno insegnato e ho usato come esempio un mio vecchio progetto. Cmq grazie dell'aiuto.
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
se è questa la riga dell'insert
$sql = "INSERT INTO articles (art_author, ecc..;
metti un var_dump subito dopo
PHP:
<?php
//...
$sql = "INSERT INTO articles (art_author, art_title, art_articles, art_date) VALUES('$author','$title', '$article', now())"; 
var_dump( $sql );
//...
?>
e verifichi che la querystringa venga scritta come deve essere
 

Jake Ikswez

Nuovo Utente
4 Dic 2013
3
0
0
Ciao ho provato come hai detto ma non mi restituisce nulla. Ho provato a mettere il var_dump qui:
PHP:
function getComments( Database $db, $id ) {
    $sql = "SELECT com_id, com_author, com_text, DATE_FORMAT (com_date,'%d %b %Y %H:%i') AS com_date FROM comments
            WHERE com_art = '$id' ORDER BY com_id DESC";
     var_dump( $sql );

    return $db->getData($sql);
}
è mi restituisce questo:
string(184) "SELECT com_id, com_author, com_text, DATE_FORMAT (com_date,'%d %b %Y %H:%i') AS com_date FROM comments WHERE com_art = 'Scelta per fotocamera compatta' ORDER BY com_id DESC"
Nella riga dove mi hai detto non succede nulla come se proprio lo ignorasse e non lo eseguisse.
 

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Ciao
Questa è la funzione per inserire i commenti nel db ed è questa che non fa assolutamente niente.
PHP:
function insertComment( Database $db, Request $formData ) {
    
    $id = $formData->post( "com_id" );
	$author = $formData->post( "com_author" );
	$comment = $formData->post( "com_text" );  
    $sql = "INSERT INTO comments (com_art, com_author, com_text, com_date) 
            VALUES ( '$author', '$comment', '$id', now())";
    var_dump( $sql );
   
    $db->query( $sql ); 
   }
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
se non fa assolutamente niente, cioe il var_dump non si vede, sembrerebbe che sia dovuto alla funzione che non viene richiamata
 

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Ciao qui teoricamente la richiamo:
PHP:
function Comments_art (Database $db, $id){
	
    $out = html("section")->attr("art_comments");
    
    $formData = new Request("post");
    $newCommentSubmitted = $formData->get("new-comment"); 
    if ( $newCommentSubmitted ) {
        
        insertComment( $db, $formData ); // qui la funzione richiamata
  
        $formData->clear();
    }

    $out->append( showForm($id));
    $out->append( showComments( $db, $id) );
    
    return $out->asHTML();
}
 

flameseeker

Utente Attivo
27 Nov 2013
699
0
0
Credo che il tuo problema dipenda dal fatto che fai il controllo di scrittura su una variabile che non esiste nel form che invii.
PHP:
    $newCommentSubmitted = $formData->get("new-comment"); 
    if ( $newCommentSubmitted ) {
        
        insertComment( $db, $formData ); // qui la funzione richiamata
  
        $formData->clear();
    }


Prova a fare così invece:
PHP:
    $newCommentSubmitted = $formData->post("com_id"); 
    if ( $newCommentSubmitted ) {
        
        insertComment( $db, $formData ); // qui la funzione richiamata
  
        $formData->clear();
    }


In ogni caso, se ancora non funziona, esamina se effettivamente $newCommentSubmitted viene riempito perché in quel caso bisognerà vedere come funziona la tua classe Request.
 
Ultima modifica:

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Cosi funziona grazie mille. Adesso ho uno strano problema invece di farmi vedere il commento con l'autore mi fa vedere il titolo dell'articolo come commento e autore il commento del form. Forse ho sbagliato qualcosa nell'inserimento dei dati nel db. Cmq strano.
 

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Ciao con il var dumpprima del if mi restituisce questo:
string(30) "Scelta per fotocamera compatta"
php found an error in your code

Error was: Headers are already sent and cannot be modified. A header has been sent before you called Request::clear() in comments_art.php, line 13
Try to look in views/comments_art.php, in line 8 . Perhaps you have a php end tag nearby? Try deleting it!
 

flameseeker

Utente Attivo
27 Nov 2013
699
0
0
Di mio, prima di buttarti sul codice, ti suggerisco di cominciare dal database e vedere se le tue tabelle sono riempite con i valori che ti aspetti.

ciao
var_dump: "carneade, chi era costui"

Come suggerisce borgo: sii scettico, esegui un controllo a tappeto dei valori che invii tramite form e che ricevi su php prima di scriverli nel database. Cerca di capire dove il tuo software confonde i valori con del sano debug insomma ;)
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
quoto flameseeker.
ricordo che il var_dump è un ottimo strumento per il debug, ma c'è un ma.
var_dump ti suggerisce (tipo di variabile e contenuto) se è giusto ok, ma se errato tocca a chi sta scivendo il codice capire il perchè e soprattutto da dove nasce l'errore

dimenticavo, l'errore
Headers are already..... spesso è dovuto all'utilizzo di header o session_start o inizializzazione di cookie DOPO che c'è stato un output html (anche un semplicissimo spazio)
 
Ultima modifica:

flameseeker

Utente Attivo
27 Nov 2013
699
0
0
Error was: Headers are already sent and cannot be modified. A header has been sent before you called Request::clear() in comments_art.php, line 13
Try to look in views/comments_art.php, in line 8 . Perhaps you have a php end tag nearby? Try deleting it!

E' normale non ti preoccupare.
Gli header, per natura del protocollo http, possono essere inviati al browser soltanto prima di iniziare a spedire i contenuti della pagina (un qualsiasi output). Il tuo metodo clear() spedisce degli header al browser evidentemente, forse per un redirect o altro, ed avendo tu usato il var_dump per controllare il valore di quella variabile hai inviato al browser un output prima di quell'header.

Come ti ho scritto, comunque, è tutto nella norma: appena avrai finito con i var_dump il problema non ci sarà più.
 

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
:fonzie::fonzie::fonzie::fonzie::fonzie::fonzie::fonzie::fonzie::fonzie::fonzie::fonzie::fonzie::fonzie:
Ora faro delle prove per capire da dove viene l'errore. Cmq il tuo aiuto è stato ottimo. Grazie ancora.
 

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Ciao, ora tutto funziona benissimo. Solo che i commenti me li fa vedere sotto tutti i articoli. Vorrei sapere come rendere questa cosa unica che per esempio se io metto il commento a un articolo lo vedo solo in quel articolo che ho commentato perchè adesso vedo i comenti sotto tutti gli articoli senza distinzione.
Se hai la possibilita di rivedere il codice e darmi dei consigli te ne sarei grato.
Cmq grazie mille dell'aiuto .
screen shot delle due tabelle che dovrebbero interagire:
Screen Shot 2013-12-09 at 17.09.17.jpgScreen Shot 2013-12-09 at 17.09.38.jpg
:)
 
Discussioni simili
Autore Titolo Forum Risposte Data
G Problema con questo script jQuery 1
O problema con dvr dahua xvr5116 IP Cam e Videosorveglianza 0
G Problema con Xampp Web Server 1
andrea barletta Problema con miniature comandi Photoshop 0
I problema con alice Posta Elettronica 0
N Problema con position absolute e overflow HTML e CSS 4
L Problema con inner join PHP 11
K [php] Problema con inner join PHP 4
K [PHP] Problema con variabili concatenate. PHP 1
O problema con query PHP 4
I problema con 2 account Posta Elettronica 1
L problema collegamento file css con html HTML e CSS 1
E Problema accesso a file con app sviluppata con MIT APP INVENTOR 2 Sviluppo app per Android 0
M Problema con Try Catch PHP 0
Sergio Unia Problema con gli eventi del mouse su una data table: Javascript 2
T PROBLEMA CON SESSIONI PHP 3
T ALTRO PROBLEMA CON ARRAY PHP PHP 1
R problema con else PHP 0
T PROBLEMA CON ARRAY PHP 8
L problema con query select PHP 2
R Problema query con ricerca id numerico PHP 2
F Problema con risposta PHP 0
S problema con recupero dati tabella mysql PHP 2
Z Problema con il mio tp-l i nk Reti LAN e Wireless 1
L Problema RAM con Tomcat 8 Apache 0
napuleone problema con sort e asort PHP 4
Z Problema con INT MySQL PHP 1
Z Problema database MySQL con XAMPP PHP 0
M Problema con controllo form in real time jQuery 6
Z Problema di sincronizzazione PAYPAL con PHP PHP 1
G Problema con Get page PHP 4
P Problema con require once PHP 6
P Problema con i package Java 1
A Problema login con Safari PHP 14
F INDESIGN: problema esportazione esecutivo per la stampa con foto B/N Webdesign e Grafica 0
S problema con css bootstrap3 HTML e CSS 4
M .load() problema con caricamenti dinamici di js Javascript 0
G Problema con eccessiva nitidezza apertura Camera Raw Photoshop 0
G Problema ------- con Query PHP 1
G Problema con Query PHP 1
T problema con select dinamica con jquery Javascript 0
S Problema con spazi bianchi HTML e CSS 5
A PROBLEMA: insert mysqli con dati Tagsinput Presentati al Forum 0
Tommy03 Problema con z-index HTML e CSS 3
M Problema inserimento parole con apostrofo nel db PHP 5
C Problema con dati meteo xml XML 1
S Problema con infrarossi videocamera IP Cam e Videosorveglianza 1
V Problema con librerie allegro5 c++ C/C++ 1
M Problema con php per calcolo costo percentuale PHP 7
S Problema con mysqli_num_rows PHP 18

Discussioni simili