Foros del Web » Programando para Internet » PHP »

no logro crear un funcion que conecte a mi bd

Estas en el tema de no logro crear un funcion que conecte a mi bd en el foro de PHP en Foros del Web. Bien, explico mi problema: Cada vez que hago alguna página dinámica cargo datos desde la base de datos (mysql), pero hay muchos queries que son ...
  #1 (permalink)  
Antiguo 24/09/2007, 14:49
Avatar de sumolari  
Fecha de Ingreso: mayo-2006
Ubicación: localhost
Mensajes: 1.367
Antigüedad: 17 años, 11 meses
Puntos: 18
no logro crear un funcion que conecte a mi bd

Bien, explico mi problema:

Cada vez que hago alguna página dinámica cargo datos desde la base de datos (mysql), pero hay muchos queries que son iguales, así que he pensado que en lugar de poner el código de cada querie (por ejemplo) para obtener el nombre de la web, creo un archivo llamado core.php que contenga una función site_config que se conecte a la base de datos y extraiga el nombre de la web y la almacene en una variable llama sitename.

Cada página que use el nombre de la web (sitename) cargará core.php con un include y llamará a la función site_config(); y con ello podrá mostrar el nombre con tan sólo un par de líneas de código, con lo que es más claro el código y si detecto un fallo en los queries sólo he de actualizar un archivo.

Bien, me pongo a ello, el Dreamweaver es el encargado de crear los queries, y crea el siguiente código:
Código PHP:
<?php require_once('Connections/SCMS.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$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;
}
}

mysql_select_db($database_SCMS$SCMS);
$query_site_config "SELECT * FROM site";
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
$row_site_config mysql_fetch_assoc($site_config);
$totalRows_site_config mysql_num_rows($site_config);
/*La variable sitename */
$sitename $row_site_config['name'];

mysql_free_result($site_config);
?>
Ese código funciona a la perfección, me explico, si le pido que me muestre la variable sitename me lo muestra bien.

Así que creo la función site_config();
Código PHP:
<?php require_once('Connections/SCMS.php'); ?>
<?php
function site_config()
{
    if (!
function_exists("GetSQLValueString")) {
    function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
    {
      
$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;
    }
    }
    
    
mysql_select_db($database_SCMS$SCMS);
    
$query_site_config "SELECT * FROM site";
    
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
    
$row_site_config mysql_fetch_assoc($site_config);
    
$totalRows_site_config mysql_num_rows($site_config);
    
/*La variable sitename */
    
$sitename $row_site_config['name'];
    echo 
$sitename;
    
    
mysql_free_result($site_config);
}
?>
Y bien, ahora creo la página que cargará la función, en este caso test.php.
Código PHP:
<?php include('core.php'); ?>
<!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=utf-8" />
<title><?php site_config(); ?></title>
</head>
<body>
<br /><div style="z-index:3" class="smallfont" align="center">LinkBacks Enabled by <a rel="nofollow" href="http://www.crawlability.com/vbseo/">vBSEO</a> 3.0.0</div><br /><div style="z-index:3" class="smallfont" align="center">LinkBacks Enabled by <a rel="nofollow" href="http://www.crawlability.com/vbseo/">vBSEO</a> 3.0.0</div></body>
</html>
Pero me da un error,
Cita:
Notice: Undefined variable: database_SCMS in C:\Servidor\www\Sumolari-CMS\core.php on line 34

Notice: Undefined variable: SCMS in C:\Servidor\www\Sumolari-CMS\core.php on line 34

Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in C:\Servidor\www\Sumolari-CMS\core.php on line 34

Notice: Undefined variable: SCMS in C:\Servidor\www\Sumolari-CMS\core.php on line 36

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\Servidor\www\Sumolari-CMS\core.php on line 36
Y así estoy, si cargo la función en core.php ocurre lo mismo. El problema me lo dan las variables, estoy seguro, pero no se cómo arreglarlo. ¿Cómo puedo hacer que el querie vaya?
  #2 (permalink)  
Antiguo 24/09/2007, 15:24
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Re: no logro crear un funcion que conecte a mi bd

Prueba hacer asi tu funcion:
Código PHP:
<?php
function site_config()
{
    require_once(
'Connections/SCMS.php');
    
mysql_select_db($database_SCMS$SCMS);
    
$query_site_config "SELECT * FROM site";
    
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
    
$row_site_config mysql_fetch_assoc($site_config);
    
$totalRows_site_config mysql_num_rows($site_config);
    
/*La variable sitename */
    
$sitename $row_site_config['name'];
    echo 
$sitename;
    
    
mysql_free_result($site_config);
}
?>
Saludos.
  #3 (permalink)  
Antiguo 24/09/2007, 23:42
Avatar de sumolari  
Fecha de Ingreso: mayo-2006
Ubicación: localhost
Mensajes: 1.367
Antigüedad: 17 años, 11 meses
Puntos: 18
Re: no logro crear un funcion que conecte a mi bd

gracias gatorV, así ya funciona. Ahora viene la segunda parte, nocesitaré tener la conexión abierta, me explico, creo unas variables (por ejemplo sitename) que contendrán valores sacados de la base de datos.

Así que en lugar de crear una función para msotrar el nombre de la página crearé dos, una para abrir la conexión y poner las variables y otra para cerrar la conexión.

Así quedaría core.php
Código PHP:
<?php
function site_config()
{
    require_once(
'Connections/SCMS.php');
    
mysql_select_db($database_SCMS$SCMS);
    
$query_site_config "SELECT * FROM site";
    
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
    
$row_site_config mysql_fetch_assoc($site_config);
    
$totalRows_site_config mysql_num_rows($site_config);
    
/*La variable sitename */
    
$sitename $row_site_config['name'];
}
function 
close_site_config()
{   
    
mysql_free_result($site_config);
}
?>
y así test.php
Código PHP:
<?php include('core.php'); ?>
<!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=utf-8" />
<title><?php site_config(); ?><?php echo $sitename?><?php echo $sitename?><?php close_site_config(); ?></title>
</head>
<body>
<br /><div style="z-index:3" class="smallfont" align="center">LinkBacks Enabled by <a rel="nofollow" href="http://www.crawlability.com/vbseo/">vBSEO</a> 3.0.0</div></body>
</html>
Y no funciona, el error:
Cita:
Notice: Undefined variable: sitename in C:\Servidor\www\Sumolari-CMS\test.php on line 8

Notice: Undefined variable: sitename in C:\Servidor\www\Sumolari-CMS\test.php on line 8

Notice: Undefined variable: site_config in C:\Servidor\www\Sumolari-CMS\core.php on line 15

Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in C:\Servidor\www\Sumolari-CMS\core.php on line 15
Gracias por vuestra ayuda!!

Edito, si defino una variable (define()) sí que logro mostrarla, pero me gustaría usar otro método.
  #4 (permalink)  
Antiguo 25/09/2007, 09:43
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Re: no logro crear un funcion que conecte a mi bd

Código PHP:
<?php
function site_config()
{
    require_once(
'Connections/SCMS.php');
    
mysql_select_db($database_SCMS$SCMS);
    
$query_site_config "SELECT * FROM site";
    
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
    
$row_site_config mysql_fetch_assoc($site_config);
    
$totalRows_site_config mysql_num_rows($site_config);
    
/*La variable sitename */
    
$sitename $row_site_config['name'];
    return 
$sitename;
}
function 
close_site_config()
{   
    
mysql_free_result($site_config);
}
?>
La usas asi:
Código PHP:
<?php
include('core.php');
$sitename site_config();
close_site_config();
?>
<!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=utf-8" />
<title><?php echo $sitename?></title>
</head>
<body>
<br /><div style="z-index:3" class="smallfont" align="center">LinkBacks Enabled by <a rel="nofollow" href="http://www.crawlability.com/vbseo/">vBSEO</a> 3.0.0</div></body>
</html>
Saludos.
  #5 (permalink)  
Antiguo 25/09/2007, 10:02
Avatar de sumolari  
Fecha de Ingreso: mayo-2006
Ubicación: localhost
Mensajes: 1.367
Antigüedad: 17 años, 11 meses
Puntos: 18
Re: no logro crear un funcion que conecte a mi bd

Muchas gracias GatorV, una cosa, entre <body> y </body> aparecen una líneas sobre vBSEO, que en mi código no aparecen, ¿han sido generadas por el foro no?

Funciona, pero me da otro error, esta vez relacionado con close_site_config()

Cita:

Notice: Undefined variable: site_config in C:\Servidor\www\Sumolari-CMS\core.php on line 16

Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in C:\Servidor\www\Sumolari-CMS\core.php on line 16

  #6 (permalink)  
Antiguo 25/09/2007, 10:43
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Re: no logro crear un funcion que conecte a mi bd

Cierto, lo que pasa es que no debes de cerrarla en otra funcion, tiene que estar en la misma funcion:
Código PHP:
<?php
function site_config()
{
    require_once(
'Connections/SCMS.php');
    
mysql_select_db($database_SCMS$SCMS);
    
$query_site_config "SELECT * FROM site";
    
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
    
$row_site_config mysql_fetch_assoc($site_config);
    
$totalRows_site_config mysql_num_rows($site_config);
    
/*La variable sitename */
    
$sitename $row_site_config['name'];
    
mysql_free_result($site_config);
    return 
$sitename;
}
?>
Saludos.
  #7 (permalink)  
Antiguo 25/09/2007, 10:52
Avatar de sumolari  
Fecha de Ingreso: mayo-2006
Ubicación: localhost
Mensajes: 1.367
Antigüedad: 17 años, 11 meses
Puntos: 18
Re: no logro crear un funcion que conecte a mi bd

Gracias, con eso ya no da error, pero me queda una última duda, ¿y si necesito más de una función?

He comprobado que cada una de las funcioens funciona bien por separado, pero juntas no, aquí está el código:
core.php
Código PHP:
<?php
function sitename()
{
    require_once(
'Connections/SCMS.php');
    
mysql_select_db($database_SCMS$SCMS);
    
$query_site_config "SELECT * FROM site";
    
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
    
$row_site_config mysql_fetch_assoc($site_config);
    
$totalRows_site_config mysql_num_rows($site_config);
    echo 
$row_site_config['name'];
    
mysql_free_result($site_config);
}
function 
echo_site($value)
{
    require_once(
'Connections/SCMS.php');
    
mysql_select_db($database_SCMS$SCMS);
    
$query_site_config "SELECT * FROM site";
    
$site_config mysql_query($query_site_config$SCMS) or die(mysql_error());
    
$row_site_config mysql_fetch_assoc($site_config);
    
$totalRows_site_config mysql_num_rows($site_config);
    
$site_value $row_site_config[$value];
    echo 
$site_value;
    
mysql_free_result($site_config);
    
}
?>
test.php
Código PHP:
<?php
include('core.php');
?>
<!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=utf-8" />
<title><?php sitename(); ?></title>
</head>
<body>
<p><?php echo_site('desc'); ?></p>
</body>
</html>

Última edición por sumolari; 25/09/2007 a las 11:02
  #8 (permalink)  
Antiguo 25/09/2007, 11:18
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Re: no logro crear un funcion que conecte a mi bd

Que error te da? En teoria deberia de funcionar perfectamente.

Saludos.
  #9 (permalink)  
Antiguo 25/09/2007, 13:18
Avatar de sumolari  
Fecha de Ingreso: mayo-2006
Ubicación: localhost
Mensajes: 1.367
Antigüedad: 17 años, 11 meses
Puntos: 18
Re: no logro crear un funcion que conecte a mi bd

Tienes razón ,se me ha pasado decir que error da, dice esto
Cita:
Notice: Undefined variable: database_SCMS in C:\Servidor\www\Sumolari-CMS\core.php on line 16

Notice: Undefined variable: SCMS in C:\Servidor\www\Sumolari-CMS\core.php on line 16

Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in C:\Servidor\www\Sumolari-CMS\core.php on line 16

Notice: Undefined variable: SCMS in C:\Servidor\www\Sumolari-CMS\core.php on line 18

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\Servidor\www\Sumolari-CMS\core.php on line 18

  #10 (permalink)  
Antiguo 25/09/2007, 14:24
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Re: no logro crear un funcion que conecte a mi bd

Cambia el require_once('Connections/SCMS.php'); en tu funcion por require('Connections/SCMS.php'); y prueba de nuevo.

Saludos.
  #11 (permalink)  
Antiguo 25/09/2007, 14:56
Avatar de sumolari  
Fecha de Ingreso: mayo-2006
Ubicación: localhost
Mensajes: 1.367
Antigüedad: 17 años, 11 meses
Puntos: 18
Re: no logro crear un funcion que conecte a mi bd

Muchísimas gracias, ya funciona a la perfección.

Realmente este foro es de gran ayuda.

Muchas gracias
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:32.