Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Johan Guse

Problema com while ou busca no DB

Recommended Posts

exibe nada fica tudo branco....

 

 

CREATE TABLE `produto` (  `id` int(5) unsigned zerofill NOT NULL auto_increment,  `nome` varchar(250) NOT NULL,  `foto1` varchar(250) NOT NULL,  `foto2` varchar(250) NOT NULL,  `preco` varchar(100) NOT NULL,  `desc` text NOT NULL,  `sessao` varchar(100) NOT NULL,  `dest` int(2) NOT NULL,  PRIMARY KEY  (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

na tabela produto não tem nem um item ainda

Compartilhar este post


Link para o post
Compartilhar em outros sites

Erro: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 'desc, sessao, dest) VALUES('','nonbre','90309_ft_grande.jpg','90309_ft_media.jpg' at line 1tkx

Compartilhar este post


Link para o post
Compartilhar em outros sites

Esta loogo acimauso como varchar mesmoabraço

exibe nada fica tudo branco....

CREATE TABLE `produto` (  `id` int(5) unsigned zerofill NOT NULL auto_increment,  `nome` varchar(250) NOT NULL,  `foto1` varchar(250) NOT NULL,  `foto2` varchar(250) NOT NULL,  `preco` varchar(100) NOT NULL,  `desc` text NOT NULL,  `sessao` varchar(100) NOT NULL,  `dest` int(2) NOT NULL,  PRIMARY KEY  (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;
na tabela produto não tem nem um item ainda

Compartilhar este post


Link para o post
Compartilhar em outros sites

Alguma variável que você ta mandando para o insert deve estar com um valor errado, da um echo no insert "com os valores" pra gente ver como está.

Compartilhar este post


Link para o post
Compartilhar em outros sites

nome texto90343_ft_grande.jpg 90343_ft_media.jpg 1,99 5 1Erro: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 'desc, sessao, dest) VALUES('','nombre','90343_ft_grande.jpg','90343_ft_media.jpg' at line 1imprimi extamente assim

Compartilhar este post


Link para o post
Compartilhar em outros sites

o mesmo while, agora não funciona em outra pagina.....

 

Uma duvida no minha tabela no mysql botei o campo id com int de tamanho 5....

ai tem uma pagina que ele pega do db o id e bota em um link (.php?codigo=00001) com o id de tamanho 5 ...

é certo isso?

pelo que me lembro não...

quando ao meu code do while....

 

<?require_once('includes/config2.php');$codigo = $_GET['codigo'];$conn=@mysql_connect($servidor,$user,$senha_db) or die ("Erro a tentar fazer conexão com servidor");mysql_select_db($bd) or die ("Não foi possivel selecionar o banco de dados");$sql_1 = "Select * From produto WHERE id='$codigo' ";$result = mysql_query( $sql_1 ) or die ("Ops, deu Erro!!!");  		while ($coluna = @mysql_fetch_array($result)) {				$codigo=$coluna[0];				$nome=$coluna[1];				$foto1=$coluna[2];				$foto2=$coluna[3];				$preco=$coluna[4];				$descri=$coluna[5];				$sessao=$coluna[6];				$dest=$coluna[7];				$descri1= nl2br($descri);}?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>:::::::::::: Ophicina das Embalagens - Área Restrita ::::::::::::</title><link href="css/estilos.css" rel="stylesheet" type="text/css" /><style type="text/css"><!--a:link {	color: #000000;	text-decoration: none;}a:visited {	text-decoration: none;	color: #000000;}a:hover {	text-decoration: none;	color: #000000;}a:active {	text-decoration: none;	color: #000000;}.txt_destaque2 {color:#000000; font-family:Arial, Helvetica, sans-serif; font-size:12px;}--></style></head><body><table width="730" border="0" align="center" cellpadding="0" cellspacing="0" class="br_painel">  <tr>	<td align="center" valign="top" bgcolor="#FFFFFF"><table width="730" height="78" border="0" cellpadding="0" cellspacing="0" class="bg_topo">	  <tr>		<td width="250" height="150" align="center" valign="middle"><img src="imgs/logo.jpg" width="150" height="173" /></td>		<td> </td>	  </tr>	</table>	  <table width="570" height="348" border="0" align="center" cellpadding="0" cellspacing="0" class="br_popup">		<tr>		  <td height="740" align="left" valign="top" bgcolor="#FFFFFF"><table width="570" height="90" border="0" cellpadding="0" cellspacing="0">			  <tr>				<td height="30" align="right" valign="middle"><a href="list_imovel.php"><img src="imgs/voltar.jpg" width="40" height="38" border="0" /></a></td>			  </tr>			  <tr>				<td height="30" align="center" valign="middle"> </td>			  </tr>			  <tr>				<td height="30" align="center" valign="middle"><strong class="txt_popup_cad_imovel">Edição de produto  </strong><strong class="eventos_fonte_02"></strong></td>			  </tr>			</table>			  <table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td height="15" align="center" valign="middle" class="txt_popup_fique_atento"> </td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0" class="txt_popup_cad_imovel">				<tr>				  <td height="25" align="right" valign="middle" class="txt_popup_cad_imovel"><b>Destaque na Home</b> </td>				  <td align="left" valign="middle">  Sim					<input name="dest" type="radio" value="1" />					Não					<input name="dhome" type="radio" value="0" /></td>				</tr>				<tr>				  <td width="118" height="25" align="right" valign="middle" class="txt_popup_cad_imovel"><strong>Nome:</strong></td>				  <td width="452" align="left" valign="middle"> 					  <input name="nome" type="text" class="txt_popup_form_cad_imovel" id="nome" value="<?=$nome?>" /></td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td width="118" height="25" align="right" valign="middle" class="txt_popup_cad_imovel"><strong>Preço:</strong></td>				  <td width="173" align="left" valign="middle"> 					  <input name="preco" type="text" class="txt_popup_form_cad_imovel" id="preco" value="<?=$preco?>" />					  </td>				  <td width="279" align="left" valign="middle" class="txt_popup_cad_imovel"> *Exemplo: R$ 15,30</td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td height="25" align="right" valign="middle" class="txt_popup_cad_imovel"><strong>Categoria:</strong></td>				  <td align="left" valign="middle"> 		<select name="sessao" class="txt_popup_form_cad_imovel_02">		  <?	  $rs_tp =& $conn->Execute("SELECT * FROM sessao ORDER BY nome ASC");	  while (!$rs_tp->EOF) {		  		  //verificando se o tipo recuperado é igual ao atribuído para o imóvel		if($rs_tp->fields['id']==$codigo){			?>			<option selected value="<?=$rs_tp->fields["id"]?>"><?=$rs_tp->fields["nome"]?>			</option>			<?			}		  else{			?>			  <option value="<?=$rs_tp->fields["id"]?>"><?=$rs_tp->fields["nome"]?></option>			  <?		}				$rs_tp->MoveNext();			  }	  ?>		</select>				  </td>				</tr>				<tr>				  <td width="118" height="25" align="right" valign="middle" class="txt_popup_cad_imovel"> </td>				  <td width="452" align="left" valign="middle"></p>					  <p> 					  <?php					  						require 'includes/config2.php';						$seleciona = "SELECT * FROM sessao";						$query = mysql_query($seleciona) or die ("ERRO!");						while ($dados = mysql_fetch_array($query)) {			   			echo $dados["nome"] . "<br />";						}						?></p></td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td height="25" align="center" valign="middle" class="txt_popup_cad_imovel"><strong>Descrição do produto:</strong></td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td height="15" align="center" valign="middle" class="txt_popup_quem_somos">*Shift 					+ Enter - Próxima linha</td>				</tr>			  </table>			<table width="570" border="0" cellpadding="0" cellspacing="0">				<tr>				  <td height="50" align="center" valign="top" bgcolor="#CCCCCC"><textarea name="noticia" id="noticia" cols="130" rows="15" class="txt_popup_quem_somos"><?=$descri?></textarea></td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td height="25" align="center" valign="middle" class="txt_popup_cad_imovel"><strong>Fotos do imóvel:</strong></td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td width="118" height="25" align="right" valign="middle" class="txt_popup_cad_imovel"><strong>Foto pequena:</strong></td>				  <td align="left" valign="middle" class="txt_popup_cad_imovel_01"> 					  <input name="foto_grande" id="foto_grande" type="file" class="txt_popup_form_cad_imovel_03" size="50" /></td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td width="118" height="25" align="right" valign="middle" class="txt_popup_cad_imovel"><strong>Foto grande:</strong></td>				  <td align="left" valign="middle" class="txt_popup_cad_imovel_01"> 					  <input name="foto_media" id="foto_media" type="file" class="txt_popup_form_cad_imovel_03" size="50" /></td>				</tr>			  </table>			<table width="570" border="0" cellspacing="0" cellpadding="0">				<tr>				  <td width="118" height="25" align="right" valign="middle" class="txt_popup_cad_imovel"> </td>				  <td align="left" valign="middle"> </td>				</tr>			  </table>			<table width="570" border="0" cellpadding="0" cellspacing="0">				<tr>				  <td height="30" align="center" valign="middle"><input name="Submit2" type="submit" class="txt_popup_quem_somos" value="Cadastrar" /></td>				</tr>			</table></td>		</tr>	  </table>	  <br />	<br /></td>  </tr></table><br /></body></html>

 

While do select que não rola.... os dados são exibidos no teste, mas ali no select não rola nada

aparece ">fields["nome"]?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Johan Guse, no início do code tem a conexão com o BD e logo em seguida um while:

 

PHP
.....

 

$sql_1 = "Select * From produto WHERE id='$codigo' ";

$result = mysql_query( $sql_1 ) or die ("Ops, deu Erro!!!");  

 

        while ($coluna = @mysql_fetch_array($result)) {

                $codigo=$coluna[0];

                $nome=$coluna[1];

                $foto1=$coluna[2];

                $foto2=$coluna[3];

                $preco=$coluna[4];

                $descri=$coluna[5];

                $sessao=$coluna[6];

                $dest=$coluna[7];

                $descri1= nl2br($descri);

 

}

Geralmente o while é utilizado quando temos diversas linhas retornadas em uma consulta; queremos executar uma ação até que determinada condição seja satisfeita. No seu caso será retornada apenas uma linha, pois na consulta já está definido que deve buscar apenas um produto de acordo com o código informado.

 

Uma aplicação mais útil seria montar as opções de um select, pegando os valores do BD.

 

Leia aqui http://br.php.net/manual/pt_BR/control-structures.while.php

 

No caso do seu select vazio, o script também tem funções que não estão no code, aconselho usar mysql_query, mysql_num_rows e mysql_fetch_array

Compartilhar este post


Link para o post
Compartilhar em outros sites

Beleza.....

Mas meu problem é no print dos itens.. não tá rolando como é pra ser

 

agora fiz um while e não sai nada:

 

<?					require 'admin/includes/config2.php';					$seleciona = "SELECT * FROM sessao";					$query = mysql_query($seleciona) or die ("ERRO!");					while ($dados = mysql_fetch_array($query)) {					?>					  <tr>						<td width="5%" align="left" valign="top"><img src="imgs/seta_categorias.gif" width="7" height="14" border="0" /></td>						<td width="95%" align="left" valign="middle" class="txtArialMenu"><a href="categoria.php?id=<? echo $dados['id']; ?>"><? echo $dados['nome']; ?></a></td>					  </tr>					  <tr>						<td height="9" colspan="2" align="center" valign="top" class="bgpontos"><img src="1x1.gif" width="1" height="1" /></td>						</tr>					 <? } ?>

Num faz while nem um !

Já no teste que fiz.. sai certin

<?php 		require 'admin/includes/config2.php';		$seleciona = "SELECT * FROM sessao";		$query = mysql_query($seleciona) or die ("ERRO!");		while ($dados = mysql_fetch_array($query)) {				echo $dados["id"] . "<br />";		}?>

1

2

3

4

 

sai assim

Compartilhar este post


Link para o post
Compartilhar em outros sites

PHP
<?php

        require 'admin/includes/config2.php';

        $seleciona = "SELECT * FROM sessao";

        $query = mysql_query($seleciona) or die ("ERRO!");

?>

<table>

<?php

        while ($dados = mysql_fetch_array($query)) {

?>                    <tr>

                        <td width="5%" align="left" valign="top"><img src="imgs/seta_categorias.gif" width="7" height="14" border="0" /></td>

                        <td width="95%" align="left" valign="middle" class="txtArialMenu"><a href="categoria.php?id=<? echo $dados['id']; ?>"><? echo $dados['nome']; ?></a></td>

                      </tr>

                      <tr>

                        <td height="9" colspan="2" align="center" valign="top" class="bgpontos"><img src="1x1.gif" width="1" height="1" /></td>

                        </tr>

                     <? } ?>

                                         </table>

 

O campo nome existe na tabela? Copia o code acima e testa, pois aqui funcionou.

Compartilhar este post


Link para o post
Compartilhar em outros sites

O meu último post foi referente ao while, agora você está mostrando que tem outro erro. Com o code que te passei, deu certo?

Nesse caso a mensagem de erro alerta que está faltando um } no código, se você organizar o mesmo, poderá ver se realmente falta uma chave fechando ou se tem uma chave abrindo a mais.

Compartilhar este post


Link para o post
Compartilhar em outros sites

cara, botei o codigo acima que você me passou em uma page sozinho...deu a mesma coisaParse error: parse error, unexpected $end in D:\programs\EasyPHP 2.0b1\www\giu\index2.php on line 17

Compartilhar este post


Link para o post
Compartilhar em outros sites

Qual o conteúdo do seu config2.php? O code que passei não tem esse erro, a única diferença entre nossos scripts é o include que você faz. O problema pode estar no seu config2.php.

Compartilhar este post


Link para o post
Compartilhar em outros sites
<?php$servidor= "localhost";$bd = "ophicina";$tabela ="login"; $user = "root"; $senha_db = ""; $moquette = @mysql_connect($servidor,$user,$senha_db) or die ("Erro a tentar fazer conexão com servidor");if (!defined("_CONNECT_INC")) {	define("_CONNECT_INC", 1);	require_once(dirname(__FILE__)."/adodb/adodb.inc.php");	$conn = &ADONewConnection("mysql");   if ($conn->Connect("localhost", "root", "", "ophicina")==false) {		echo "<html>\n<head>\n</head>\n<body>\n";		echo "<script Language=\"Javascript\">\n";		echo "	alert(\"Erro na conexão com banco de dados\");\n";		echo "</script>\n";		echo "</body>\n</html>\n";		exit;	}	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;} //endif $data=date("d/m/Y");   $hora=date('h:i:s');   $data_e_hora = "$data às $hora hs";   $fica = '#FFFFFF';$cima = '#FFFF33'; ?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.