Bienvenido a datoweb.com!! En este foro podrás encontrar ayuda sobre diseño y desarrollo web en general. Si quieres formar parte de esta comunidad para pedir ayuda o colaborar ayudando a otros usuarios del foro solo tienes que registrarte desde el siguiente enlace: Registrarse en el Foro

Ejemplos de como usar mysqli de manera fácil

Vamos a ver unos ejemplos de como usar mysqli de una manera muy sencilla sobre todo si estamos acostumbrados a usar mysql, con estos ejemplos también podremos pasar o migrar nuestros proyectos de mysql a mysqli.

Ejemplos:
<?php

//CONEXIÓN A LA BASE DE DATOS
$hostname_db = "host";
$database_db = "nombre";
$username_db = "usuario";
$password_db = "password";
//Conectar a la base de datos
$conexion = mysqli_connect($hostname_db, $username_db, $password_db);
//Seleccionar la base de datos
mysqli_select_db($conexion,$database_db) or die ("Ninguna DB seleccionada");



//CONSULTA A LA BASE DE DATOS
$accion_nm="SELECT * FROM tabla WHERE columna1='algo'";
$consulta_nm=mysqli_query($conexion,$accion_nm);
$datos_nm=mysqli_fetch_assoc($consulta_nm);

//Cantidad de registros
$cantidad_nm=mysqli_num_rows($consulta_nm);
//Sacar datos con $datos;

mysqli_free_result($consulta_nm);



//ACTUALIZAR REGISTRO
$accion_nm = "UPDATE tabla SET columna1='algo' WHERE columna2='algo'";
$consulta_nm = mysqli_query($conexion,$accion_nm) or die(mysqli_error());



//BORRAR REGISTRO
$accion_nm = "DELETE FROM tabla WHERE columna1='algo'";
$consulta_nm = mysqli_query($conexion,$accion_nm) or die(mysqli_error());



//INSERTAR REGISTRO
$accion_nm = "INSERT INTO tabla (columna1) VALUES ('algo')";
$consulta_nm = mysqli_query($conexion,$accion_nm) or die(mysqli_error());

?>
Descargar ejemplo

La verdad es que no varia mucho, en lo que mas suele atascarse la gente es en la forma de hacer el query ya que antes (con mysql) se hacia así:
$consulta=mysql_query($accion,$conexion);
y ahora (con mysqli) se hace así:
$consulta=mysqli_query($conexion,$accion);
Entre otras cosas!

Salu2
Editado
5
Puntos
30146
Visitas
8
Resp
Por alber hace 102 meses
Administrador
Respuesta #1
Agrego a este hilo como formatear cadena con función GetSQLValueString en mysqli:
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  //Iniciamos la variable $conexion
  global $conexion;

  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  //Agregamos $conexion en las funciones mysqli_real_escape_string y mysqli_escape_string
  $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($conexion,$theValue) : mysqli_escape_string($conexion,$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;
}
0
Puntos
Por alber hace 77 meses
Administrador
Respuesta #2
genial! Me uno al hilo!
0
Puntos
Por Soraya hace 69 meses
Principiante Sitio web
Respuesta #3
Soraya dijo: genial! Me uno al hilo!
yeah!! salu2
1
Puntos
Por alber hace 69 meses
Administrador
Respuesta #4

hola voy a poner codigo antigu con nuevo mysqli a ver si parto bien :)

0
Puntos
Por claudioam hace 66 meses
Principiante
Respuesta #5
// antes con mysql era

mysql_select_db($database_conexion, $conexion);
			$query_SacarDatosWeb = "SELECT * FROM datos_a WHERE nombre ='miweb'";
			$SacarDatosWeb = mysql_query($query_SacarDatosWeb, $conexion) or die(mysql_error());
			$row_SacarDatosWeb = mysql_fetch_assoc($SacarDatosWeb);
			$totalRows_SacarDatosWeb = mysql_num_rows($SacarDatosWeb);
			
			
			$urlWeb=$row_SacarDatosWeb['url']; //se  sacan variables
		    $nombreWeb=$row_SacarDatosWeb['nombre'];


y ahota con mysqli es:


			$accion_nm = "SELECT * FROM datos_a WHERE nombre ='miweb'";
			$consulta_nm = mysqli_query($conexion,$accion_nm);
			$datos_nm = mysqli_fetch_assoc($accion_nm);
			$cantidad_nm = mysqli_num_rows($accion_nm);
			
			
			$urlWeb=$datos_nm['url']; //se  sacan variables
		    $nombreWeb=$datos_nm['nombre'];
			
			
			
			mysqli_free_result($consulta_nm);

0
Puntos
Por claudioam hace 66 meses
Principiante
Respuesta #6
Excelente, gran post, de verdad me ayuda muchísimo, esta intentado migrar mi web a mysqli y no había encontrado algo que de verdad me ayudara...gracias
1
Puntos
Por seoranking hace 40 meses
Principiante Sitio web
Respuesta #7
Hola.
Soy de los muchos que reuíamos a cambiar a mysqli, pero ahora me resulta imperativo.
Mi pregunta puede sonar tonta o demasiado básica, pero me es urgente saber como migrar querries de mysql a mysqli como la de este ejemplo..
Tengo este códico funcional en mysql, ¿cómo lo cambio a mysqli?
$datos = mysql_query("SELECT * FROM temas ORDER BY Nombre") 
or die(mysql_error());
Print "--código html--"; 
while($info = mysql_fetch_array( $datos ))
{
Print "--código html--".$info['Tema'] . "--código html--"; 
Print "--código html--".$info['Nombre'] . "--código html--"; 
}
Gracias Mil
0
Puntos
Por Nor hace 31 meses
Principiante
Respuesta #8
alber dijo: Agrego a este hilo como formatear cadena con función GetSQLValueString en mysqli:
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  //Iniciamos la variable $conexion
  global $conexion;

  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  //Agregamos $conexion en las funciones mysqli_real_escape_string y mysqli_escape_string
  $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($conexion,$theValue) : mysqli_escape_string($conexion,$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;
}
Muchas gracias!!!
0
Puntos
Por htmlmasters hace 13 meses
Principiante Sitio web
Compartir en facebook
Compartir en twitter
Compartir
Para comentar Inicia sesión o Registrate