Foros del Web » Programando para Internet » PHP »

problema de variable

Estas en el tema de problema de variable en el foro de PHP en Foros del Web. <table width="99%" border="0" cellspacing="0" cellpadding="3"> <tr> <td width="50%"><span class="letra">Categorias</span> <strong> <?php if($_SESSION['MM_UserGroup']=="admin"){ ?> <a href="insectar categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">Insectar_categoria <?php } ?> </a></strong></td> <td width="26%" ...
  #1 (permalink)  
Antiguo 31/12/2012, 09:10
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
problema de variable

<table width="99%" border="0" cellspacing="0" cellpadding="3">
<tr>
<td width="50%"><span class="letra">Categorias</span>
<strong>
<?php if($_SESSION['MM_UserGroup']=="admin"){
?>
<a href="insectar categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">Insectar_categoria
<?php } ?>
</a></strong></td>
<td width="26%" align="center"><span class="centro3">Publicaciones totales</span></td>
<td width="24%" align="center"><span class="centro3">Ultimo Post</span></td>
</tr>
<?php do { ?>

<?php
mysql_select_db($database_libre, $libre);
$publicacion_sql = "SELECT mensaje FROM mensajes WHERE tema = " .
$row_temas['id_tema'];
$ultimo_sql = "SELECT autor,fecha FROM mensajes WHERE tema = " .
$row_temas['id_tema'] . " ORDER BY fecha DESC LIMIT 1";
$uPost = mysql_query($ultimo_sql) or die(mysql_error ());
$pTotales = mysql_query($publicacion_sql) or die(mysql_error());
?>
<tr>
<td><a href="categorias.php?id_categorias=<?php echo $row_categorias['id_categoria']; ?>&amp;nombre_user=<?php echo $row_usuarios['nombre_user']; ?>"><strong><?php echo $row_categorias['nombre']; ?></strong></a><strong><a href="insectar categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">
<?php if($_SESSION['MM_UserGroup']=="admin"){
?>
</a><a href="borrar_confirma.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">Eliminar </a><a href="insectar categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">
<?php } ?>
</a><a href="editar_categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>&amp;categoria=<?php echo $row_categorias['id_categoria']; ?>">
<?php if($_SESSION['MM_UserGroup']=="admin"){
?>
Editar</a><a href="borrar_confirma.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">
<?php } ?>
</a></strong><br />
Descricion: <?php echo $row_categorias['descripcion']; ?></td>


<td align="center"><?php echo mysql_num_rows($pTotales);?></td>
<td align="center"><?php $up = mysql_fetch_assoc($uPost);
echo $up {'fecha'};
echo '<br/>';
echo $up {'autor'};?></td>





</tr>
<?php } while ($row_categorias = mysql_fetch_assoc($categorias)); ?>
</table>

Me da este error:

Notice: Undefined variable: row_temas in C:\xampp\htdocs\libre\acceso.php on line 233

Notice: Undefined variable: row_temas in C:\xampp\htdocs\libre\acceso.php on line 235
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 'ORDER BY fecha DESC LIMIT 1' at line 1

Alguien lo puede corregir porfavor
  #2 (permalink)  
Antiguo 31/12/2012, 09:20
Avatar de jotaincubus  
Fecha de Ingreso: mayo-2005
Ubicación: Medellin - Colombia
Mensajes: 1.797
Antigüedad: 18 años, 11 meses
Puntos: 394
Respuesta: problema de variable

En realidad no es un error, php te esta diciendo que esas variables no están definidas.

Para solucionarlo podrías guardar el dato del array dentro de una variable local:

Código PHP:
Ver original
  1. $id_tema = $row_temas['id_tema'];
  2. $publicacion_sql = "SELECT mensaje FROM mensajes WHERE tema = $id_tema";
__________________
Por que existe gente que no agradece después de que se le ha brindado tiempo y ayuda ???
  #3 (permalink)  
Antiguo 31/12/2012, 09:21
Avatar de carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 14 años
Puntos: 461
Respuesta: problema de variable

el mensaje es claro no esta definida la variable $row_temas['id_tema'], en el fragmento del código que muestras no esta definida imagino que tienes mas código anterior a lo que muestras verifica que estes definiendo esta variable o incluso (imagino que viene de una consulta) verifica que la consulta que te da ese valor este trayendo valores, sino simplemente con una verificación en el código
Código PHP:
Ver original
  1. if(isset($row_temas['id_tema'])) {
  2.    /*la consult que estas realizando donde necesitas ese valor*/
  3. }
saludos
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way
  #4 (permalink)  
Antiguo 31/12/2012, 09:59
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
Respuesta: problema de variable

este es todo el codigo la variable seria categorias

Código:
<?php require_once('Connections/libre.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "entrada.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "admin,premium,user";
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && false) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "error.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  $updateSQL = sprintf("UPDATE categorias SET nombre=%s, descripcion=%s WHERE id_categoria=%s",
                       GetSQLValueString($_POST['nombre'], "text"),
                       GetSQLValueString($_POST['descripcion'], "text"),
                       GetSQLValueString($_POST['id_categoria'], "int"));

  mysql_select_db($database_libre, $libre);
  $Result1 = mysql_query($updateSQL, $libre) or die(mysql_error());

  $updateGoTo = "acceso.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  $updateSQL = sprintf("UPDATE categorias SET nombre=%s, descripcion=%s WHERE id_categoria=%s",
                       GetSQLValueString($_POST['nombre'], "text"),
                       GetSQLValueString($_POST['descripcion'], "text"),
                       GetSQLValueString($_POST['id_categoria'], "int"));

  mysql_select_db($database_libre, $libre);
  $Result1 = mysql_query($updateSQL, $libre) or die(mysql_error());

  $updateGoTo = "acceso.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

$colname_usuarios = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_usuarios = $_SESSION['MM_Username'];
}
mysql_select_db($database_libre, $libre);
$query_usuarios = sprintf("SELECT * FROM libre WHERE nombre_user = %s", GetSQLValueString($colname_usuarios, "text"));
$usuarios = mysql_query($query_usuarios, $libre) or die(mysql_error());
$row_usuarios = mysql_fetch_assoc($usuarios);
$totalRows_usuarios = mysql_num_rows($usuarios);

mysql_select_db($database_libre, $libre);
$query_carpetas = "SELECT * FROM folders";
$carpetas = mysql_query($query_carpetas, $libre) or die(mysql_error());
$row_carpetas = mysql_fetch_assoc($carpetas);
$totalRows_carpetas = mysql_num_rows($carpetas);

mysql_select_db($database_libre, $libre);
$query_menssages = "SELECT * FROM messages";
$menssages = mysql_query($query_menssages, $libre) or die(mysql_error());
$row_menssages = mysql_fetch_assoc($menssages);
$totalRows_menssages = mysql_num_rows($menssages);

mysql_select_db($database_libre, $libre);
$query_categorias = "SELECT * FROM categorias";
$categorias = mysql_query($query_categorias, $libre) or die(mysql_error());
$row_categorias = mysql_fetch_assoc($categorias);
$totalRows_categorias = mysql_num_rows($categorias);
?>
<!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"><!-- InstanceBegin template="/Templates/base.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- InstanceBeginEditable name="doctitle" -->
<title>acceso</title>
<!-- InstanceEndEditable -->
<link href="tables.css" rel="stylesheet" type="text/css" />
<!-- InstanceBeginEditable name="head" -->
<style type="text/css">
.centro1 {text-align: center;
}
.centro {
	text-align: center;
}
.centro {
	text-align: center;
}
.letra {
	font-size: 14px;
}
.centro3 {	text-align: center;
}
.centro3 {	text-align: center;
}
</style>
<!-- InstanceEndEditable -->
<style type="text/css">
body {
	background-image: url();
	background-color: #D3E4E5;
}
</style>
</head>

<body>
<table width="54%" border="0" align="center" cellpadding="3" cellspacing="0">
  <tr>
    <td align="center" valign="middle"><img src="imagen/logo_final_.jpg" width="877" height="195" align="middle" /></td>
  </tr>
  <tr>
    <td><!-- InstanceBeginEditable name="panel de control" -->
      <table width="99%" border="0" cellspacing="0" cellpadding="3">
        <tr>
          <td width="50%"><span class="letra">Categorias</span>
            <strong>
            <?php if($_SESSION['MM_UserGroup']=="admin"){
							?>
            <a href="insectar categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">Insectar_categoria
            <?php  }   ?>             
          </a></strong></td>
          <td width="26%" align="center"><span class="centro3">Publicaciones totales</span></td>
          <td width="24%" align="center"><span class="centro3">Ultimo Post</span></td>
        </tr>
        <?php do { ?>
        
        <?php
		mysql_select_db($database_libre, $libre);
$publicacion_sql = "SELECT mensaje FROM mensajes WHERE categoria = " .
$row_temas['id_categoria']; 
$ultimo_sql = "SELECT autor,fecha FROM mensajes WHERE tema = " .
$row_temas['id_tema'] . " ORDER BY fecha DESC LIMIT 1";
$uPost = mysql_query($ultimo_sql) or die(mysql_error ()); 
$pTotales = mysql_query($publicacion_sql) or die(mysql_error());
		?>        
          <tr>
            <td><a href="categorias.php?id_categorias=<?php echo $row_categorias['id_categoria']; ?>&amp;nombre_user=<?php echo $row_usuarios['nombre_user']; ?>"><strong><?php echo $row_categorias['nombre']; ?></strong></a><strong><a href="insectar categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">
              <?php if($_SESSION['MM_UserGroup']=="admin"){
							?>
            </a><a href="borrar_confirma.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">Eliminar </a><a href="insectar categoria.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">
            <?php  }   ?>
  #5 (permalink)  
Antiguo 31/12/2012, 10:10
Avatar de carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 14 años
Puntos: 461
Respuesta: problema de variable

La variable $row_temas no existe en tu código por eso el error que te da el interprete de php (o yo no lo vi si nos dices donde esta definida sería bueno :) ).

Además de esto como concejo cada vez que vas a hacer una consulta vuelves a seleccionar la base de datos eso no es bueno si ya la seleccionaste una vez porque repetir lo mismo si no hay cambios?? de hecho lo normal es que uno tenga un archivo donde hace la conexión y lo incluya, lo hace mas mantenible al momento de cambiar los parámetros de la base de datos cuando se sube al server, saludos
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way
  #6 (permalink)  
Antiguo 31/12/2012, 10:46
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
Respuesta: problema de variable

Mira no se casi de codigo en el video tutorial que sigo solo ponen este codigo
no hace nada mas y a el le funciona,
podiras modificarme o decirme donde fallo y como lo resuelvo un saludo

esto el del videotutorial dice que lo pongamos
mysql_select_db($database_libre, $libre);


<?php
mysql_select_db($database_libre, $libre);
$publicacion_sql = "SELECT mensaje FROM mensajes WHERE categoria = " .
$row_temas['id_categoria'];
$ultimo_sql = "SELECT autor,fecha FROM mensajes WHERE tema = " .
$row_temas['id_tema'] . " ORDER BY fecha DESC LIMIT 1";
$uPost = mysql_query($ultimo_sql) or die(mysql_error ());
$pTotales = mysql_query($publicacion_sql) or die(mysql_error());
?>

Un saludo
  #7 (permalink)  
Antiguo 31/12/2012, 11:34
Avatar de carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 14 años
Puntos: 461
Respuesta: problema de variable

imagino que es porque están intentando enseñar en un solo archivo, pero normalmente uno cuando esta comenzando tiene algo así
conexion.php
Código PHP:
Ver original
  1. function conectar() {
  2.     $conect = mysql_connect('host', 'dbUser', 'password') or die('Error al conectar ' .mysql_error());
  3.     mysql_select_db('tuDb') or die('error al seleccionar la base de datos ' . mysql_error());
  4. }

archivo.php donde trbajaras

Código PHP:
Ver original
  1. require_once 'conexion.php';
  2.  /*el fragmento que tengas arriba*/
  3. //llamas a la función para que conecte con mysql una vez que llamaste a esta mientras no cierres la conexión no es necesario volverla a llamar en el mismo archivo
  4. conectar();
  5. $publicacion_sql = "SELECT mensaje FROM mensajes WHERE categoria = " .
  6. $row_temas['id_categoria'];
  7. $ultimo_sql = "SELECT autor,fecha FROM mensajes WHERE tema = " .
  8. $row_temas['id_tema'] . " ORDER BY fecha DESC LIMIT 1";
  9. $uPost = mysql_query($ultimo_sql) or die(mysql_error ());
  10. $pTotales = mysql_query($publicacion_sql) or die(mysql_error());

ahora yendo a tu problema en específico, en tu código en ningún sitio hay una variable que se llame $row_temas por eso siempre te dará ese warning, es como que yo te diga busca la manzana en un sitio donde solo hay peras que me vas a decir tu??

$row_temas['id_tema'] que debería de tener?? el resultado de alguna consulta?? si es así simplemente has la consulta y asignala a la variable.

Una vez vayas avanzando y aprendiendo el lenguaje iras buscando la manera de separar la logica de programación de la parte de la vista, saludos
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way
  #8 (permalink)  
Antiguo 01/01/2013, 06:13
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
Respuesta: problema de variable

Vale perdona por ser tan bruta.

podrias ponerme ese codigo para poder copiarlo estoy nula en esto
  #9 (permalink)  
Antiguo 01/01/2013, 08:30
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 9 meses
Puntos: 1567
Respuesta: problema de variable

Cita:
Iniciado por yolanda16568 Ver Mensaje
Vale perdona por ser tan bruta.

podrias ponerme ese codigo para poder copiarlo estoy nula en esto
@yolanda16568
Creo que el mejor consejo que se te puede dar es
http://www.mclibre.org/consultar/php/index.html
ó si alguien conoce, otro link a un buen tutorial

__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.

Etiquetas: mysql, sql, variables, usuarios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:58.