<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel><title>unijimpe &#187; MySQL</title> <atom:link href="http://blog.unijimpe.net/category/mysql/feed/" rel="self" type="application/rss+xml" /><link>http://blog.unijimpe.net</link> <description>Desarrollo Web, SEO, Adsense</description> <lastBuildDate>Mon, 28 Nov 2011 03:18:21 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>PHP con MySQL: Eliminar Registros en MySQL</title><link>http://blog.unijimpe.net/php-con-mysql-eliminar-registros-en-mysql/</link> <comments>http://blog.unijimpe.net/php-con-mysql-eliminar-registros-en-mysql/#comments</comments> <pubDate>Wed, 12 Oct 2011 04:42:56 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[delete]]></category> <category><![CDATA[HTML]]></category> <category><![CDATA[Javascript]]></category> <category><![CDATA[select]]></category> <category><![CDATA[sql]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1258</guid> <description><![CDATA[<p>En artículos previos hemos explicado como interactuar con MySQL utilizando PHP, desde consultar, insertar y editar registros, ahora veremos como eliminar registros de manera sencilla. Si es que no has leído los artículos anteriores te recomiendo &#8230;</p>]]></description> <content:encoded><![CDATA[<p>En artículos previos hemos explicado como interactuar con MySQL utilizando PHP, desde consultar, insertar y editar registros, ahora veremos como eliminar registros de manera sencilla. Si es que no has leído los artículos anteriores te recomiendo revisar:</p><ul><li><a href="http://blog.unijimpe.net/php-con-mysql-introduccion-a-sql/">PHP con MySQL: Introducción a SQL</a></li><li><a href="http://blog.unijimpe.net/php-con-mysql-crear-una-conexion-a-mysql/">PHP con MySQL: Crear una conexión a MySQL</a></li><li><a href="http://blog.unijimpe.net/php-con-mysql-insertar-datos-en-mysql/">PHP con MySQL: Insertar datos en MySQL</a></li><li><a href="http://blog.unijimpe.net/php-con-mysql-consultar-datos-en-mysql/">PHP con MySQL: Consultar datos en MySQL</a></li><li><a href="http://blog.unijimpe.net/php-con-mysql-editar-registros-con-mysql/">PHP con MySQL: Editar Registros con MySQL</a></li></ul><p>Para eliminar registros seguiremos los siguientes pasos: primero haremos un listado de todos los registros de la tabla elegida, luego en el listado agregaremos un enlace a un archivo <em>delete.php</em> que se encargará de hacer la eliminación. Antes de eliminar el registro le preguntaremos al usuario si desea proceder con la eliminación. Finalmente eliminaremos el registro y redireccionaremos al usuario a listado de registros.</p><p><strong>Crear el Listado de Registros</strong></p><p>Para nuestro ejemplo utilizaremos la base de datos de ejemplo que contiene una tabla llamada <em>empresa</em> (Descargar el <a href="http://samples.unijimpe.net/demo-empresa.sql">Script SQL</a>). Creamos una consulta a la tabla 'empresa' y lo mostramos en una tabla HTML con un enlace a eliminar el registro.</p><div class="syntax_hilite"><div id="html-3"><div class="html"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php</div></li><li style="color:#26536A;"><div style="">// conexión a mysql</div></li><li style="color:#3A6A8B;"><div style="">require<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"conexion.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">require<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"funciones.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">// consulta de registros</div></li><li style="color:#26536A;"><div style="">$query = <span style="color: #ff0000;">"SELECT * FROM empresa ORDER BY nombre ASC"</span>;</div></li><li style="color:#3A6A8B;"><div style="">$queEmp = mysql_query<span style="color: #66cc66;">&#40;</span>$query, $conexion<span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">?<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/html.html"><span style="color: #000000;">&lt;html&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/head.html"><span style="color: #000000;">&lt;head&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/title.html"><span style="color: #000000;">&lt;title&gt;</span></a></span>Listado de Empresas<span style="color: #009900;"><span style="color: #000000;">&lt;/title&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/head&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/body.html"><span style="color: #000000;">&lt;body&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/table.html"><span style="color: #000000;">&lt;table&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php while <span style="color: #66cc66;">&#40;</span>$rsEmp = mysql_fetch_assoc<span style="color: #66cc66;">&#40;</span>$quEmp<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> ?<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/tr.html"><span style="color: #000000;">&lt;tr&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/td.html"><span style="color: #000000;">&lt;td&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'nombre'</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;/td&gt;</span></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/td.html"><span style="color: #000000;">&lt;td&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'direccion'</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;/td&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/td.html"><span style="color: #000000;">&lt;td&gt;</span></a></span><span style="color: #009900;"><a href="http://december.com/html/4/element/a.html"><span style="color: #000000;">&lt;a</span></a> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">"editar.php?id=&lt;?php echo $rsEmp['id']; ?&gt;</span>&quot;&gt;Editar<span style="color: #009900;">&lt;/a&gt;</span><span style="color: #009900;">&lt;/td&gt;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;">&lt;td&gt;</span><span style="color: #009900;">&lt;a href="</span>#<span style="color: #ff0000;">" onclick="</span>delEmpresa<span style="color: #66cc66;">&#40;</span><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'id'</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span>);&quot;&gt;Eliminar<span style="color: #009900;"><span style="color: #000000;">&lt;/a&gt;</span></span><span style="color: #009900;"><span style="color: #000000;">&lt;/td&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color: #009900;"><span style="color: #000000;">&lt;/tr&gt;</span></span></div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php <span style="color: #66cc66;">&#125;</span> ?<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/table&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/script.html"><span style="color: #000000;">&lt;script</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text/javascript"</span><span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">function delEmpresa(id) {</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; if (window.confirm(&quot;Aviso:\nDesea eliminar el registro seleccionado?&quot;))&nbsp;{</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &nbsp; &nbsp; window.location = &quot;delete.php?action=del<span style="color: #ddbb00;">&amp;id=&quot;+id;</span>&nbsp; &nbsp;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; }</div></li><li style="color:#3A6A8B;"><div style="">}</div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/script&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/body&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/html&gt;</span></span></div></li></ol></div></div></div><p></p><p>Hay que notar que en lugar de colocar un enlace directo a <em>delete.php</em> estamos llamando a una función Javascript <code>delEmpresa</code>, esta función le pregunta al usuario si esta seguro de eliminar el registro (Para evitar eliminar registros de manera accidental). Si el usuario acepta entonces redireccionamos a otra página donde pasamos el id del registro que deseamos eliminar.</p><p><strong>Eliminar el registro</strong></p><p>Creamos un archivo llamado <em>delete.php</em> el cual recibe dos parámetros: el identificador del registro un otro parámetro para verificar que acción se quiere realizar. Creamos la consulta para eliminar el registro y finalmente redireccionar al listado de registros.</p><div class="syntax_hilite"><div id="php-4"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// file: delete.php</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"funciones.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$idempresa</span> = getParam<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_GET</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"id"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"-1"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$action</span> = getParam<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_GET</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"action"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp;</div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$action</span> == <span style="color:#FF0000;">"del"</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span> = <span style="color:#FF0000;">"DELETE FROM empresa WHERE id = "</span>.sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$idempresa</span>, <span style="color:#FF0000;">"int"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$sql</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/header"><span style="color:#000066;">header</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"location: listado.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Notar que estamos utilizando dos funciones especiales:</p><ul><li><code>getParam</code> permite filtrar los datos enviados por el usuario y definir un valor por defecto (En el ejemplo si no se ha enviado el parámetro id devuelve como valor -1).</li><li><code>sqlValue</code> permite formatear el tipo de dato que acepta la consulta (Por ejemplo se puede definir que el campo es entero <em>int</em>, si el usuario envía un cadena de texto esta función la convertirá a un entero).</li></ul><p>Para finalizar les dejo los archivos con el código fuente que incluye el archivo de conexión y las funciones utilizadas en nuestro ejemplo.</p><p style="text-align:left;"><a href="http://blog.unijimpe.net/download/php-mysql-delete.zip" title="PHP con MySQL: Eliminar registros"><img src="http://blog.unijimpe.net/btdown.png" border="0"></a></p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/php-con-mysql-eliminar-registros-en-mysql/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>PHP con MySQL: Editar Registros con MySQL</title><link>http://blog.unijimpe.net/php-con-mysql-editar-registros-con-mysql/</link> <comments>http://blog.unijimpe.net/php-con-mysql-editar-registros-con-mysql/#comments</comments> <pubDate>Tue, 01 Mar 2011 03:53:54 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[consulta]]></category> <category><![CDATA[query]]></category> <category><![CDATA[select]]></category> <category><![CDATA[sql]]></category> <category><![CDATA[update]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1256</guid> <description><![CDATA[<p>Continuando con la serie de artículos para trabajar con datos de MySQL desde PHP, es el momento de editar los datos guardados en nuestras tablas. Para ello haremos uso de la sentencia UPDATE explicada anteriormente en &#8230;</p>]]></description> <content:encoded><![CDATA[<p>Continuando con la serie de artículos para trabajar con datos de MySQL desde PHP, es el momento de editar los datos guardados en nuestras tablas. Para ello haremos uso de la sentencia UPDATE explicada anteriormente en <a href="http://blog.unijimpe.net/php-con-mysql-introduccion-a-sql/">PHP con MySQL: Introducción a SQL</a>.</p><p><img src="http://blog.unijimpe.net/wp-content/uploads/2011/02/editar-mysql.gif" alt="" title="editar-mysql" width="313" height="163" /></p><p>El proceso será: primero mostrar un formulario con los datos que tenemos guardados, luego el usuario puede modificar los datos y enviar el formulario. Continuando, recibimos los datos enviados desde el formulario, con ello creamos la consulta SQL y lo enviamos a MySQL con la función <em>mysql_query</em>.</p><p><strong>Preparar el listado de datos</strong></p><p>Para nuestro ejemplo seguiremos utilizando la base de datos de ejemplo (Pueden descargar el <a href="http://samples.unijimpe.net/demo-empresa.sql">Script SQL</a>). Entonces haremos un listado de todos los registros de la tabla <em>empresa</em> y para cada registro crearemos un enlace hacia otra página donde se hará la edición de datos.</p><div class="syntax_hilite"><div id="html-10"><div class="html"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php</div></li><li style="color:#26536A;"><div style="">// creamos la conexión a mysql</div></li><li style="color:#3A6A8B;"><div style="">require<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"conexion.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">require<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"funciones.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">// hacemos la consulta de registros</div></li><li style="color:#26536A;"><div style="">$query = <span style="color: #ff0000;">"SELECT * FROM empresa ORDER BY nombre ASC"</span>;</div></li><li style="color:#3A6A8B;"><div style="">$queEmp = mysql_query<span style="color: #66cc66;">&#40;</span>$query, $conexion<span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">?<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/html.html"><span style="color: #000000;">&lt;html&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/head.html"><span style="color: #000000;">&lt;head&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/title.html"><span style="color: #000000;">&lt;title&gt;</span></a></span>Listado de Empresas<span style="color: #009900;"><span style="color: #000000;">&lt;/title&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/head&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/body.html"><span style="color: #000000;">&lt;body&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/table.html"><span style="color: #000000;">&lt;table&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php while <span style="color: #66cc66;">&#40;</span>$rsEmp = mysql_fetch_assoc<span style="color: #66cc66;">&#40;</span>$quEmp<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> ?<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/tr.html"><span style="color: #000000;">&lt;tr&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/td.html"><span style="color: #000000;">&lt;td&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'nombre'</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;/td&gt;</span></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/td.html"><span style="color: #000000;">&lt;td&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'direccion'</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span><span style="color: #009900;"><span style="color: #000000;">&lt;/td&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/td.html"><span style="color: #000000;">&lt;td&gt;</span></a></span><span style="color: #009900;"><a href="http://december.com/html/4/element/a.html"><span style="color: #000000;">&lt;a</span></a> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">"editar.php?id=&lt;?php echo $rsEmp['id']; ?&gt;</span>&quot;&gt;Editar<span style="color: #009900;">&lt;/a&gt;</span><span style="color: #009900;">&lt;/td&gt;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color: #009900;">&lt;/tr&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color: #009900;">&lt;?php } ?&gt;</span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;">&lt;/table&gt;</span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;">&lt;/body&gt;</span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;">&lt;/html&gt;</span> </span></div></li></ol></div></div></div><p></p><p>Como se puede ver hemos creado un enlace al archivo <em>editar.php</em> al cual le pasamos como parámetro GET el identificador del registro.</p><p><strong>Consultando los detalles del Registro</strong></p><p>El siguiente paso es obtener los datos del registro seleccionado, para ello utilizamos como filtro el identificador del registro el cual lo estamos pasando como parámetro GET.</p><div class="syntax_hilite"><div id="php-11"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// editar.php</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"funciones.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$idempresa</span> = getParam<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_GET</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"id"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"-1"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#FF9933; font-style:italic;">// consultamos los datos</span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$sql</span> = <span style="color:#FF0000;">"SELECT * FROM empresa WHERE id = "</span>.sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$idempresa</span>, <span style="color:#FF0000;">"int"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$queEmp</span> = <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$sql</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$rsEmp</span> = <a href="http://www.php.net/mysql_fetch_assoc"><span style="color:#000066;">mysql_fetch_assoc</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$queEmp</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$total</span> = <a href="http://www.php.net/mysql_num_rows"><span style="color:#000066;">mysql_num_rows</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$queEmp</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$total</span> == <span style="color:#CC66CC;color:#800000;">0</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// si no hay datos redireccionamos al listado</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/header"><span style="color:#000066;">header</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"location: listado.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/exit"><span style="color:#000066;">exit</span></a>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Notar que estamos utilizando la función creada anteriormente <em>sqlValue</em>, la cual formatea los datos para ser compatibles con el tipo de dato aceptado por la base de datos. En el ejemplo el id lo pasamos como un número entero. Finalmente antes de mostrar los datos verificamos que nuestra consulta ha devuelto resultados, si no hay resultados, el registro no existe y redireccionamos a la lista de empresas.</p><p><strong>Creando el Formulario</strong></p><p>Ahora mostramos el formulario con los datos recién consultados, para ello imprimimos los datos de la variable <em>$rsEmp</em> y accedemos a cada campo como si fuera un array:</p><div class="syntax_hilite"><div id="html-12"><div class="html"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/form.html"><span style="color: #000000;">&lt;form</span></a> <span style="color: #000066;">method</span>=<span style="color: #ff0000;">"post"</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">"editar.php?action=edit"</span><span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/strong.html"><span style="color: #000000;">&lt;strong&gt;</span></a></span>Nombre<span style="color: #009900;"><span style="color: #000000;">&lt;/strong&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"nombre"</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">"&lt;?php echo $rsEmp['nombre']; ?&gt;</span>&quot; /&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;">&lt;strong&gt;</span>Dirección<span style="color: #009900;">&lt;/strong&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;">&lt;input type="</span><span style="color: #000066;">text</span><span style="color: #ff0000;">" name="</span>direccion<span style="color: #ff0000;">" value="</span><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'direccion'</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span>&quot; /&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/strong.html"><span style="color: #000000;">&lt;strong&gt;</span></a></span>Telefono<span style="color: #009900;"><span style="color: #000000;">&lt;/strong&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"telefono"</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">"&lt;?php echo $rsEmp['telefono']; ?&gt;</span>&quot; /&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;">&lt;input type="</span>hidden<span style="color: #ff0000;">" id="</span><span style="color: #000066;">id</span><span style="color: #ff0000;">" name="</span><span style="color: #000066;">id</span><span style="color: #ff0000;">" value="</span><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"id"</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span>&quot; /&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/button.html"><span style="color: #000000;">&lt;button</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"submit"</span><span style="color: #000000;">&gt;</span></a></span>Guardar<span style="color: #009900;"><span style="color: #000000;">&lt;/button&gt;</span></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/button.html"><span style="color: #000000;">&lt;button</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"reset"</span><span style="color: #000000;">&gt;</span></a></span>Limpiar<span style="color: #009900;"><span style="color: #000000;">&lt;/button&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/form&gt;</span></span></div></li></ol></div></div></div><p></p><p>Como se puede ver, hemos incluido un campo oculto con el identificador del registro, es oculto por que este dato no se puede editar y nos servirá como condición para actualizar los datos.</p><p><strong>Guardando los Datos</strong></p><p>El paso final es recibir los datos del formulario, crear la consulta para actualizar los datos. Para ello primero recogemos la variable <em>action</em> y verificamos si se esta intentando editar.</p><div class="syntax_hilite"><div id="php-13"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$action</span> = getParam<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_GET</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"action"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$action</span> == <span style="color:#FF0000;">"edit"</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$idempresa</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"id"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"int"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$nombre</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"nombre"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"text"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$direccion</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"direccion"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"text"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$telefono</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"telefono"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"int"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span> = <span style="color:#FF0000;">"UPDATE empresa SET "</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span>.= <span style="color:#FF0000;">"nombre="</span>.<span style="color:#0000FF;">$nombre</span>.<span style="color:#FF0000;">", direccion="</span>.<span style="color:#0000FF;">$direccion</span>.<span style="color:#FF0000;">", telefono="</span>.<span style="color:#0000FF;">$telefono</span>.<span style="color:#FF0000;">" "</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span>.= <span style="color:#FF0000;">"WHERE id="</span>.<span style="color:#0000FF;">$idempresa</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$sql</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/header"><span style="color:#000066;">header</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"location: listado.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Lo único que hemos hecho es crear la consulta en base a los datos recibidos del formulario, luego de ello redireccionamos al listado de registros.</p><p><strong>Uniendo todos los elementos</strong></p><p>Unimos todo el código para obtener el script para editar registros.</p><div class="syntax_hilite"><div id="html-14"><div class="html"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php</div></li><li style="color:#26536A;"><div style="">require<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"conexion.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">require<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"funciones.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp;</div></li><li style="color:#3A6A8B;"><div style="">$idempresa = getParam<span style="color: #66cc66;">&#40;</span>$_GET<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"id"</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #ff0000;">"-1"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">$action = getParam<span style="color: #66cc66;">&#40;</span>$_GET<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"action"</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #ff0000;">""</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp;</div></li><li style="color:#26536A;"><div style="">if <span style="color: #66cc66;">&#40;</span>$action == <span style="color: #ff0000;">"edit"</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; $idempresa = getParam<span style="color: #66cc66;">&#40;</span>$_POST<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"id"</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #ff0000;">"-1"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; $nombre = sqlValue<span style="color: #66cc66;">&#40;</span>$_POST<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"nombre"</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #ff0000;">"text"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; $direccion = sqlValue<span style="color: #66cc66;">&#40;</span>$_POST<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"direccion"</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #ff0000;">"text"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; $telefono = sqlValue<span style="color: #66cc66;">&#40;</span>$_POST<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"telefono"</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #ff0000;">"int"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; $sql = <span style="color: #ff0000;">"UPDATE empresa SET "</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; $sql.= <span style="color: #ff0000;">"nombre="</span>.$nombre.<span style="color: #ff0000;">", direccion="</span>.$direccion.<span style="color: #ff0000;">", telefono="</span>.$telefono.<span style="color: #ff0000;">" "</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; $sql.= <span style="color: #ff0000;">"WHERE id="</span>.$idempresa;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; mysql_query<span style="color: #66cc66;">&#40;</span>$sql, $conexion<span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; header<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"location: listado.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #66cc66;">&#125;</span></div></li><li style="color:#26536A;"><div style="">&nbsp;</div></li><li style="color:#3A6A8B;"><div style="">$sql = <span style="color: #ff0000;">"SELECT * FROM empresa WHERE id = "</span>.sqlValue<span style="color: #66cc66;">&#40;</span>$idempresa, <span style="color: #ff0000;">"int"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">$queEmp = mysql_query<span style="color: #66cc66;">&#40;</span>$sql, $conexion<span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">$rsEmp = mysql_fetch_assoc<span style="color: #66cc66;">&#40;</span>$queEmp<span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">$total = mysql_num_rows<span style="color: #66cc66;">&#40;</span>$queEmp<span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">if <span style="color: #66cc66;">&#40;</span>$total == <span style="color: #cc66cc;color:#800000;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; header<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"location: listado.php"</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; exit;</div></li><li style="color:#26536A;"><div style=""><span style="color: #66cc66;">&#125;</span></div></li><li style="color:#3A6A8B;"><div style="">?<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/html.html"><span style="color: #000000;">&lt;html&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/head.html"><span style="color: #000000;">&lt;head&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/title.html"><span style="color: #000000;">&lt;title&gt;</span></a></span>Editar Empresa<span style="color: #009900;"><span style="color: #000000;">&lt;/title&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/head&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/body.html"><span style="color: #000000;">&lt;body&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/h3.html"><span style="color: #000000;">&lt;h3&gt;</span></a></span>Editar Empresa<span style="color: #009900;"><span style="color: #000000;">&lt;/h3&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/form.html"><span style="color: #000000;">&lt;form</span></a> <span style="color: #000066;">method</span>=<span style="color: #ff0000;">"post"</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">"editar.php?action=edit"</span><span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/strong.html"><span style="color: #000000;">&lt;strong&gt;</span></a></span>Nombre<span style="color: #009900;"><span style="color: #000000;">&lt;/strong&gt;</span></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"nombre"</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">"&lt;?php echo $rsEmp['nombre']; ?&gt;</span>&quot; /&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;">&lt;strong&gt;</span>Dirección<span style="color: #009900;">&lt;/strong&gt;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;">&lt;input type="</span><span style="color: #000066;">text</span><span style="color: #ff0000;">" name="</span>direccion<span style="color: #ff0000;">" value="</span><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'direccion'</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span>&quot; /&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/strong.html"><span style="color: #000000;">&lt;strong&gt;</span></a></span>Telefono<span style="color: #009900;"><span style="color: #000000;">&lt;/strong&gt;</span></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"telefono"</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">"&lt;?php echo $rsEmp['telefono']; ?&gt;</span>&quot; /&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;">&lt;input type="</span>hidden<span style="color: #ff0000;">" id="</span><span style="color: #000066;">id</span><span style="color: #ff0000;">" name="</span><span style="color: #000066;">id</span><span style="color: #ff0000;">" value="</span><span style="color: #000000;">&lt;</span></a>?php echo $rsEmp<span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">"id"</span><span style="color: #66cc66;">&#93;</span>; ?<span style="color: #000000;">&gt;</span></a></span>&quot; /&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/button.html"><span style="color: #000000;">&lt;button</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"submit"</span><span style="color: #000000;">&gt;</span></a></span>Guardar<span style="color: #009900;"><span style="color: #000000;">&lt;/button&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/button.html"><span style="color: #000000;">&lt;button</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"reset"</span><span style="color: #000000;">&gt;</span></a></span>Limpiar<span style="color: #009900;"><span style="color: #000000;">&lt;/button&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/form&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/body&gt;</span></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/html&gt;</span></span></div></li></ol></div></div></div><p></p><p>Como se puede ver, editar datos de MySQL es sencillo, hay que crear la consulta y para ello concatenamos los datos enviados desde el formulario. En el ejemplo solo tenemos tres campos pero podríamos aplicarlo a cualquier cantidad de campos.</p><p style="text-align:left;"><a href="http://blog.unijimpe.net/download/update-mysql.zip" title="Update MySQL"><img src="http://blog.unijimpe.net/btdown.png" border="0"></a></p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/php-con-mysql-editar-registros-con-mysql/feed/</wfw:commentRss> <slash:comments>18</slash:comments> </item> <item><title>PHP con MySQL: Consultar datos en MySQL</title><link>http://blog.unijimpe.net/php-con-mysql-consultar-datos-en-mysql/</link> <comments>http://blog.unijimpe.net/php-con-mysql-consultar-datos-en-mysql/#comments</comments> <pubDate>Thu, 03 Feb 2011 05:50:40 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[buscador]]></category> <category><![CDATA[consulta]]></category> <category><![CDATA[like]]></category> <category><![CDATA[query]]></category> <category><![CDATA[select]]></category> <category><![CDATA[sql]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1249</guid> <description><![CDATA[<p>Consultar o extraer datos es una de las tareas mas comunes al interactuar con bases de datos, de esta forma podemos extraer los datos previamente almacenados, por ejemplo para mostrar la lista de productos de una &#8230;</p>]]></description> <content:encoded><![CDATA[<p>Consultar o extraer datos es una de las tareas mas comunes al interactuar con bases de datos, de esta forma podemos extraer los datos previamente almacenados, por ejemplo para mostrar la lista de productos de una tienda online o también para un buscador de documentos o el login de usuarios.</p><p><strong>Requerimientos</strong></p><p>Antes de continuar, es necesario tener una conexión abierta a MySQL, para ello pueden leer <a href="http://blog.unijimpe.net/php-con-mysql-crear-una-conexion-a-mysql/">Crear una conexión a MySQL</a> y luego crear la base de datos de ejemplo con el siguiente <a href="http://samples.unijimpe.net/demo-empresa.sql">Script SQL</a>.</p><p><strong>Extrayendo datos de MySQL</strong></p><p>Para extraer datos utilizaremos la función <em>mysql_query</em> mediante la cual enviamos un consulta SQL. Entonce primero incluimos el archivo para crear la conexión e inmediatamente creamos la consulta para extraer todos los datos de las empresas en nuestra base de datos.</p><div class="syntax_hilite"><div id="php-24"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// incluimos la conexión</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// creamos la consulta</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$query</span> = <span style="color:#FF0000;">"SELECT * FROM empresa ORDER BY nombre ASC"</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// enviamos la consulta a MySQL</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$queEmp</span> = <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$query</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li></ol></div></div></div><p></p><p>También se puede agregar una sentencia para mostrar si hay algún error en la conexión o consulta.</p><div class="syntax_hilite"><div id="php-25"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$query</span> = <span style="color:#FF0000;">"SELECT * FROM empresa ORDER BY nombre ASC"</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$queEmp</span> = <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$query</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span> or <a href="http://www.php.net/die"><span style="color:#000066;">die</span></a><span style="color:#006600;">&#40;</span><a href="http://www.php.net/mysql_error"><span style="color:#000066;">mysql_error</span></a><span style="color:#006600;">&#40;</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span>;</div></li></ol></div></div></div><p></p><p><strong>Mostrando los Datos</strong></p><p>El siguiente paso es mostrar los datos extraídos en la consulta, para ello podemos utilizar <em>mysql_fetch_assoc</em> el cual devolverá un array asociativo con el siguiente registro devuelto por la consulta. Entonces para mostrar todos los registros devueltos por la consulta se tendría:</p><div class="syntax_hilite"><div id="php-26"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">while</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$resEmp</span> = <a href="http://www.php.net/mysql_fetch_assoc"><span style="color:#000066;">mysql_fetch_assoc</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$queEmp</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp;<a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$resEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'nombre'</span><span style="color:#006600;">&#93;</span>.<span style="color:#FF0000;">"&lt;br&gt;"</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Donde se puede ver que para acceder a cada campo del registro lo hacemos como un array donde le pasamos el nombre del campo que deseamos acceder (En el ejemplo estamos mostrando todos los nombres de las empresas consultadas).</p><p>Ahora, solo depende como deseamos mostrar los datos para modificar nuestro script. Por ejemplo si deseamos mostrar los datos como una lista tendríamos</p><div class="syntax_hilite"><div id="php-27"><div class="php"><ol><li style="color:#3A6A8B;"><div style="">&lt;ul&gt;</div></li><li style="color:#26536A;"><div style=""><span style="color:#000000;">&lt;?php</span> <span style="color:#616100;">while</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$rsEmp</span> = <a href="http://www.php.net/mysql_fetch_assoc"><span style="color:#000066;">mysql_fetch_assoc</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$quEmp</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&lt;li&gt;&lt;?php <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$rsEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'nombre'</span><span style="color:#006600;">&#93;</span>; ?&gt;&lt;/li&gt;</div></li><li style="color:#26536A;"><div style=""><span style="color:#000000;">&lt;?php</span> <span style="color:#006600;">&#125;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&lt;/ul&gt;</div></li></ol></div></div></div><p></p><p>Ahora también podríamos mostrar los resultados en una tabla o datagrid, para ello modificamos nuestro código donde utilizaremos una tabla para mostrar en varias columnas los datos consultados.</p><div class="syntax_hilite"><div id="php-28"><div class="php"><ol><li style="color:#3A6A8B;"><div style="">&lt;table&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &lt;tr&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;th&gt;Nombre&lt;/th&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;th&gt;Dirección&lt;/th&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;th&gt;Teléfono&lt;/th&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &lt;/tr&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color:#000000;">&lt;?php</span> <span style="color:#616100;">while</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$rsEmp</span> = <a href="http://www.php.net/mysql_fetch_assoc"><span style="color:#000066;">mysql_fetch_assoc</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$quEmp</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &lt;tr&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;td&gt;&lt;?php <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$rsEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'nombre'</span><span style="color:#006600;">&#93;</span>; ?&gt;&lt;/td&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;td&gt;&lt;?php <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$rsEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'direccion'</span><span style="color:#006600;">&#93;</span>; ?&gt;&lt;/td&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;td&gt;&lt;?php <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$rsEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'telefono'</span><span style="color:#006600;">&#93;</span>; ?&gt;&lt;/td&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &lt;/tr&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color:#000000;">&lt;?php</span> <span style="color:#006600;">&#125;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#26536A;"><div style="">&lt;/table&gt;</div></li></ol></div></div></div><p></p><p><strong>Crear un Buscador</strong></p><p>Ahora, podríamos crear un buscador básico de empresas, para ello creamos un formulario para ingresar el criterio de búsqueda.</p><div class="syntax_hilite"><div id="php-29"><div class="php"><ol><li style="color:#3A6A8B;"><div style="">&lt;form id=<span style="color:#FF0000;">"frbuscar"</span> method=<span style="color:#FF0000;">"get"</span> action=<span style="color:#FF0000;">""</span>&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;input name=<span style="color:#FF0000;">"criterio"</span> id=<span style="color:#FF0000;">"criterio"</span> type=<span style="color:#FF0000;">"text"</span> /&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;input type=<span style="color:#FF0000;">"submit"</span> id=<span style="color:#FF0000;">"btbuscar"</span> value=<span style="color:#FF0000;">"Buscar"</span> /&gt;</div></li><li style="color:#26536A;"><div style="">&lt;/form&gt;</div></li></ol></div></div></div><p></p><p>Antes de continuar decidimos el tipo de consulta SQL que vamos a utilizar, en nuestro caso la búsqueda será por las primeras letras del nombre, para ello utilizaremos la sentencia LIKE explicada en el artículo <a href="http://blog.unijimpe.net/php-con-mysql-introduccion-a-sql/">PHP con MySQL: Introducción a SQL</a>.</p><div class="syntax_hilite"><div id="sql-30"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">WHERE</span> nombre <span style="color: #993333;">LIKE</span> <span style="color: #ff0000;">'A%'</span></div></li></ol></div></div></div><p></p><p>Luego, una vez enviado el formulario procedemos a recuperar los datos para proceder a crear la consulta y enviarla a MySQL. Primero verificamos que se ha enviado un criterio de búsqueda luego creamos la consulta no sin antes normalizar los datos (para prevenir ataques de inyección SQL), esto lo hacemos con la función sqlValue que hemos creado en <a href="http://blog.unijimpe.net/php-con-mysql-insertar-datos-en-mysql/">PHP con MySQL: Insertar datos en MySQL</a>.</p><div class="syntax_hilite"><div id="php-31"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"funciones.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$criterio</span> = getParam<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_GET</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"criterio"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$total</span> = <span style="color:#CC66CC;color:#800000;">0</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$criterio</span> != <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$slike</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$criterio</span>.<span style="color:#FF0000;">"%"</span>, <span style="color:#FF0000;">"text"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$query</span> = <span style="color:#FF0000;">"SELECT * FROM empresa WHERE nombre like "</span>.<span style="color:#0000FF;">$slike</span>.<span style="color:#FF0000;">" ORDER BY nombre ASC"</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$queEmp</span> = <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$query</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$total</span> = <a href="http://www.php.net/mysql_num_rows"><span style="color:#000066;">mysql_num_rows</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$queEmp</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Nótese que estamos utilizando una variable <em>$total</em> donde se almacena el total de resultados devueltos por la consulta. El total de resultados se obtiene con la función <em>mysql_num_rows</em>.</p><p>Finalmente mostramos los resultados al cliente, para ello verificamos que existan resultados en la consulta. Uniendo todos los elementos tendríamos:</p><div class="syntax_hilite"><div id="php-32"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#000000;">&lt;?php</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"funciones.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$criterio</span> = getParam<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_GET</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"criterio"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$total</span> = <span style="color:#CC66CC;color:#800000;">0</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$criterio</span> != <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$slike</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$criterio</span>.<span style="color:#FF0000;">"%"</span>, <span style="color:#FF0000;">"text"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$query</span> = <span style="color:#FF0000;">"SELECT * FROM empresa WHERE nombre like "</span>.<span style="color:#0000FF;">$slike</span>.<span style="color:#FF0000;">" ORDER BY nombre ASC"</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$queEmp</span> = <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$query</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$total</span> = <a href="http://www.php.net/mysql_num_rows"><span style="color:#000066;">mysql_num_rows</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$queEmp</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#006600;">&#125;</span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#000000;">?&gt;</span></div></li><li style="color:#26536A;"><div style="">&lt;html&gt;</div></li><li style="color:#3A6A8B;"><div style="">&lt;head&gt;</div></li><li style="color:#26536A;"><div style="">&lt;title&gt;Consultar datos en MySQL&lt;/title&gt;</div></li><li style="color:#3A6A8B;"><div style="">&lt;/head&gt;</div></li><li style="color:#26536A;"><div style="">&lt;body&gt;</div></li><li style="color:#3A6A8B;"><div style="">&lt;h3&gt;Buscador de&nbsp; Empresas&lt;/h3&gt;</div></li><li style="color:#26536A;"><div style="">&lt;form id=<span style="color:#FF0000;">"frbuscar"</span> method=<span style="color:#FF0000;">"get"</span> action=<span style="color:#FF0000;">""</span>&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;input name=<span style="color:#FF0000;">"criterio"</span> id=<span style="color:#FF0000;">"criterio"</span> type=<span style="color:#FF0000;">"text"</span> /&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;input type=<span style="color:#FF0000;">"submit"</span> id=<span style="color:#FF0000;">"btbuscar"</span> value=<span style="color:#FF0000;">"Buscar"</span> /&gt;</div></li><li style="color:#3A6A8B;"><div style="">&lt;/form&gt;</div></li><li style="color:#26536A;"><div style=""><span style="color:#000000;">&lt;?php</span> <span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$total</span>&gt; <span style="color:#CC66CC;color:#800000;">0</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&lt;em&gt;Total de Resultados: <span style="color:#000000;">&lt;?php</span> <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$total</span>; ?&gt;&lt;/em&gt;</div></li><li style="color:#26536A;"><div style="">&lt;table&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &lt;tr&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;th&gt;Nombre&lt;/th&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;th&gt;Dirección&lt;/th&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;th&gt;Teléfono&lt;/th&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &lt;/tr&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color:#000000;">&lt;?php</span> <span style="color:#616100;">while</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$rsEmp</span> = <a href="http://www.php.net/mysql_fetch_assoc"><span style="color:#000066;">mysql_fetch_assoc</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$quEmp</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &lt;tr&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;td&gt;&lt;?php <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$rsEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'nombre'</span><span style="color:#006600;">&#93;</span>; ?&gt;&lt;/td&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &lt;td&gt;&lt;?php <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$rsEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'direccion'</span><span style="color:#006600;">&#93;</span>; ?&gt;&lt;/td&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &lt;td&gt;&lt;?php <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$rsEmp</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'telefono'</span><span style="color:#006600;">&#93;</span>; ?&gt;&lt;/td&gt;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &lt;/tr&gt;</div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color:#000000;">&lt;?php</span> <span style="color:#006600;">&#125;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&lt;/table&gt;</div></li><li style="color:#26536A;"><div style=""><span style="color:#000000;">&lt;?php</span> <span style="color:#006600;">&#125;</span> <span style="color:#000000;">?&gt;</span></div></li><li style="color:#3A6A8B;"><div style="">&lt;p&gt;&amp;nbsp;&lt;/p&gt;</div></li><li style="color:#26536A;"><div style="">&lt;/body&gt;</div></li><li style="color:#3A6A8B;"><div style="">&lt;/html&gt;</div></li></ol></div></div></div><p></p><p>Como pueden ver no es complicado hacer consultas a MySQL, solo debemos crear la cadena con la consulta SQL y luego enviarla utilizando la función <em>mysql_query</em>. Lo siguiente solo depende de como deseamos mostrar la información resultante de nuestra consulta.</p><p>Para finalizar les dejo los archivos fuente de los ejemplos desarrollados en este artículo para que puedan hacer sus pruebas, seguir experimentando y completar su aprendizaje.</p><p style="text-align:left;"><a href="http://blog.unijimpe.net/download/php-mysql-select.zip" title="PHP y MYSQL - Select"><img src="http://blog.unijimpe.net/btdown.png" border="0"></a></p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/php-con-mysql-consultar-datos-en-mysql/feed/</wfw:commentRss> <slash:comments>15</slash:comments> </item> <item><title>PHP con MySQL: Insertar datos en MySQL</title><link>http://blog.unijimpe.net/php-con-mysql-insertar-datos-en-mysql/</link> <comments>http://blog.unijimpe.net/php-con-mysql-insertar-datos-en-mysql/#comments</comments> <pubDate>Mon, 13 Dec 2010 04:16:30 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[base de datos]]></category> <category><![CDATA[insert]]></category> <category><![CDATA[sql]]></category> <category><![CDATA[validar]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1251</guid> <description><![CDATA[<p>Continuando con la serie de artículos dedicados a explicar como trabajar PHP con MySQL, ahora nos toca explicar como insertar datos o registros en nuestras tablas de MySQL.</p><p><strong>Requerimientos</strong></p><p>Para guardar datos en MySQL es necesario &#8230;</p>]]></description> <content:encoded><![CDATA[<p>Continuando con la serie de artículos dedicados a explicar como trabajar PHP con MySQL, ahora nos toca explicar como insertar datos o registros en nuestras tablas de MySQL.</p><p><strong>Requerimientos</strong></p><p>Para guardar datos en MySQL es necesario primero <a href="http://blog.unijimpe.net/php-con-mysql-crear-una-conexion-a-mysql/">crear una conexión con MySQL</a>, también necesitamos una base de datos de ejemplo el cual pueden crear con el siguiente <a href="http://samples.unijimpe.net/demo-empresa.sql">script SQL</a> y finalmente <a href="http://blog.unijimpe.net/php-con-mysql-introduccion-a-sql/">conocimientos básicos de SQL</a>.</p><h3>Conceptos Básicos</h3><p>PHP provee funciones nativas que permiten interactuar con MySQL, para el proceso de insertar registros utilizaremos las siguientes funciones.</p><ul><li><strong>mysql_query</strong> permite enviar cualquier consulta SQL (<em>SELECT</em>, <em>INSERT</em>, <em>UPDATE</em>, etc.) desde PHP.</li><li><strong>mysql_insert_id</strong> devuelve el identificador del último registro ingresado.</li></ul><p>Entonces si deseamos insertar una nueva empresa en nuestra tabla de ejemplo tendríamos:</p><div class="syntax_hilite"><div id="php-39"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// abrimos la conexión</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// insertarmos el registro</span></div></li><li style="color:#26536A;"><div style=""><a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"INSERT INTO empresa (nombre, direccion) VALUES ('Apple', '1 Infinite Loop')"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// mostramos el ID del registro</span></div></li><li style="color:#26536A;"><div style=""><a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <a href="http://www.php.net/mysql_insert_id"><span style="color:#000066;">mysql_insert_id</span></a><span style="color:#006600;">&#40;</span><span style="color:#006600;">&#41;</span>;</div></li></ol></div></div></div><p></p><p>Como pueden ver la creación de datos es sencilla, solo necesitamos crear la consulta adecuada y la enviamos mediante <em>mysql_query</em>.</p><h3>Ejemplo Práctico</h3><p>Veamos un ejemplo práctico, donde mediante un formulario en HTML registraremos los datos de las empresas.</p><p><strong>Creando el Formulario</strong></p><p>Para nuestro ejemplo creamos un formulario con tres campos (nombre, dirección y teléfono) con dos botones uno para enviar los datos y otro para limpiar el formulario.</p><div class="syntax_hilite"><div id="html-40"><div class="html"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/form.html"><span style="color: #000000;">&lt;form</span></a> <span style="color: #000066;">method</span>=<span style="color: #ff0000;">"post"</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">"agregar-empresa.php"</span><span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; Nombre&nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">"nombre"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"nombre"</span> /<span style="color: #000000;">&gt;</span></a></span><span style="color: #009900;"><a href="http://december.com/html/4/element/br.html"><span style="color: #000000;">&lt;br</span></a> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; Direcci<span style="color: #ddbb00;">&amp;oacute;</span>n&nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">"direccion"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"direccion"</span> /<span style="color: #000000;">&gt;</span></a></span><span style="color: #009900;"><a href="http://december.com/html/4/element/br.html"><span style="color: #000000;">&lt;br</span></a> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; Tel<span style="color: #ddbb00;">&amp;eacute;</span>fono&nbsp; &nbsp;<span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">"telefono"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"telefono"</span> /<span style="color: #000000;">&gt;</span></a></span><span style="color: #009900;"><a href="http://december.com/html/4/element/br.html"><span style="color: #000000;">&lt;br</span></a> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/button.html"><span style="color: #000000;">&lt;button</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"submit"</span><span style="color: #000000;">&gt;</span></a></span>Guardar<span style="color: #009900;"><span style="color: #000000;">&lt;/button&gt;</span></span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color: #009900;"><a href="http://december.com/html/4/element/button.html"><span style="color: #000000;">&lt;button</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"reset"</span><span style="color: #000000;">&gt;</span></a></span>Limpiar<span style="color: #009900;"><span style="color: #000000;">&lt;/button&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/form&gt;</span></span></div></li></ol></div></div></div><p></p><p><strong>Procesando los Datos</strong></p><p>El siguiente paso, es verificar si se están enviando datos desde un formulario para luego crear la consulta concatenando los datos enviados para finalmente guardar los datos con la función <em>mysql_query</em>.</p><div class="syntax_hilite"><div id="php-41"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// file: insert-demo2.php</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$status</span> = <span style="color:#FF0000;">""</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><a href="http://www.php.net/isset"><span style="color:#000066;">isset</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"nombre"</span><span style="color:#006600;">&#93;</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$nombre</span> = <span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"nombre"</span><span style="color:#006600;">&#93;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$direccion</span> = <span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"direccion"</span><span style="color:#006600;">&#93;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$telefono</span> = <span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"telefono"</span><span style="color:#006600;">&#93;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// Creamos la consulta&nbsp; </span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span> = <span style="color:#FF0000;">"INSERT INTO empresa (nombre, direccion, telefono) "</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span>.= <span style="color:#FF0000;">"VALUES ('"</span>.<span style="color:#0000FF;">$nombre</span>.<span style="color:#FF0000;">"', '"</span>.<span style="color:#0000FF;">$direccion</span>.<span style="color:#FF0000;">"', '"</span>.<span style="color:#0000FF;">$telefono</span>.<span style="color:#FF0000;">"')"</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// enviamos la consulta</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$sql</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$status</span> = <span style="color:#FF0000;">"ok"</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Uniendo el código obtenemos nuestro primer ejemplo funcionando para agregar registros desde un formulario.</p><p><strong>Filtrando los Datos</strong></p><p>El ejemplo anterior, funciona pero tiene un problema y es que el usuario podría haber ingresado datos inválidos (Por ejemplo texto donde solo se aceptan números) o también enviar código SQL para atacar a nuestra base de datos. Por ello antes de utilizar los datos enviados por el usuario es necesario antes normalizar estos datos.</p><p>Creamos una función llamada <strong>sqlValue</strong>, esta se encarga de convertir al tipo de dato correcto y agregarle los apostrofes necesarios para los textos y fechas.</p><div class="syntax_hilite"><div id="php-42"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// file: funciones.php</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#000000;">function</span> sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span>, <span style="color:#0000FF;">$type</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color:#0000FF;">$value</span> = <a href="http://www.php.net/get_magic_quotes_gpc"><span style="color:#000066;">get_magic_quotes_gpc</span></a><span style="color:#006600;">&#40;</span><span style="color:#006600;">&#41;</span> ? <a href="http://www.php.net/stripslashes"><span style="color:#000066;">stripslashes</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span><span style="color:#006600;">&#41;</span> : <span style="color:#0000FF;">$value</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color:#0000FF;">$value</span> = <a href="http://www.php.net/function_exists"><span style="color:#000066;">function_exists</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"mysql_real_escape_string"</span><span style="color:#006600;">&#41;</span> ? <a href="http://www.php.net/mysql_real_escape_string"><span style="color:#000066;">mysql_real_escape_string</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span><span style="color:#006600;">&#41;</span> : <a href="http://www.php.net/mysql_escape_string"><span style="color:#000066;">mysql_escape_string</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color:#616100;">switch</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$type</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#616100;">case</span> <span style="color:#FF0000;">"text"</span>:</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#0000FF;">$value</span> = <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span> != <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span> ? <span style="color:#FF0000;">"'"</span> . <span style="color:#0000FF;">$value</span> . <span style="color:#FF0000;">"'"</span> : <span style="color:#FF0000;">"NULL"</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#616100;">break</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#616100;">case</span> <span style="color:#FF0000;">"int"</span>:</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#0000FF;">$value</span> = <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span> != <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span> ? <a href="http://www.php.net/intval"><span style="color:#000066;">intval</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span><span style="color:#006600;">&#41;</span> : <span style="color:#FF0000;">"NULL"</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#616100;">break</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#616100;">case</span> <span style="color:#FF0000;">"double"</span>:</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#0000FF;">$value</span> = <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span> != <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span> ? <span style="color:#FF0000;">"'"</span> . <a href="http://www.php.net/doubleval"><span style="color:#000066;">doubleval</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span><span style="color:#006600;">&#41;</span> . <span style="color:#FF0000;">"'"</span> : <span style="color:#FF0000;">"NULL"</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#616100;">break</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#616100;">case</span> <span style="color:#FF0000;">"date"</span>:</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#0000FF;">$value</span> = <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$value</span> != <span style="color:#FF0000;">""</span><span style="color:#006600;">&#41;</span> ? <span style="color:#FF0000;">"'"</span> . <span style="color:#0000FF;">$value</span> . <span style="color:#FF0000;">"'"</span> : <span style="color:#FF0000;">"NULL"</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; &nbsp; <span style="color:#616100;">break</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; <span style="color:#006600;">&#125;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; <span style="color:#616100;">return</span> <span style="color:#0000FF;">$value</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Esta función recibe dos parámetros, el primero el dato que deseamos normalizar y el segundo el tipo de dato (<em>text</em>, <em>int</em>, <em>double</em>, <em>date</em>). Luego vamos a modificar nuestro primer script para verificar los datos antes de guardarlos.</p><div class="syntax_hilite"><div id="php-43"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#FF9933; font-style:italic;">// file: insert-demo3.php</span></div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"conexion.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">require</span><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"funciones.php"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$status</span> = <span style="color:#FF0000;">""</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><a href="http://www.php.net/isset"><span style="color:#000066;">isset</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"nombre"</span><span style="color:#006600;">&#93;</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$nombre</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"nombre"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"text"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$direccion</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"direccion"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"text"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$telefono</span> = sqlValue<span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">"telefono"</span><span style="color:#006600;">&#93;</span>, <span style="color:#FF0000;">"int"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span> = <span style="color:#FF0000;">"INSERT INTO empresa (nombre, direccion, telefono) "</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$sql</span>.= <span style="color:#FF0000;">"VALUES ("</span>.<span style="color:#0000FF;">$nombre</span>.<span style="color:#FF0000;">", "</span>.<span style="color:#0000FF;">$direccion</span>.<span style="color:#FF0000;">", "</span>.<span style="color:#0000FF;">$telefono</span>.<span style="color:#FF0000;">")"</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$sql</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$status</span> = <span style="color:#FF0000;">"ok"</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Unimos nuevamente el código y obtenemos una nueva forma de guardar datos en MySQL esta vez verificando los tipos de datos antes de guardarlos.</p><p>Haciendo pequeñas modificaciones podríamos guardar los datos de cualquier formulario, no importa la cantidad de datos o la complejidad de los mismos, todo este proceso se puede resumir en armar correctamente la consulta SQL para insertar los datos.</p><p><strong>Depurar los INSERTS</strong></p><p>Si tienen problemas en la creación de sus consultas por que no insertan o generan un error, lo mas sencillo es imprimir la consulta antes de enviarla a MySQL y detener la ejecución del script PHP.</p><div class="syntax_hilite"><div id="php-44"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$sql</span> = <span style="color:#FF0000;">"INSERT INTO empresa (nombre, direccion, telefono) "</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$sql</span>.= <span style="color:#FF0000;">"VALUES ("</span>.<span style="color:#0000FF;">$nombre</span>.<span style="color:#FF0000;">", "</span>.<span style="color:#0000FF;">$direccion</span>.<span style="color:#FF0000;">", "</span>.<span style="color:#0000FF;">$telefono</span>.<span style="color:#FF0000;">")"</span>;</div></li><li style="color:#3A6A8B;"><div style=""><a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$sql</span>;</div></li><li style="color:#26536A;"><div style=""><a href="http://www.php.net/exit"><span style="color:#000066;">exit</span></a>;</div></li><li style="color:#3A6A8B;"><div style=""><a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$sql</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li></ol></div></div></div><p></p><p>La consulta devuelta podemos revisarla y detectar algún error de sintaxis, también podríamos ejecutarla directamente en algún cliente de MySQL que tengamos para verificar si hace la inserción correctamente.</p><p style="text-align:left;"><a href="http://blog.unijimpe.net/download/insert.zip" title="Insertar en MySQL"><img src="http://blog.unijimpe.net/btdown.png" border="0"></a></p><p><strong>Nota Final</strong></p><p>Para mejorar aún mas nuestro script para insertar datos, podríamos agregar validación de formularios. Ello lo podríamos hacer desde el lado del cliente mediante una librería javascript para validar formulario (Por ejemplo: <a href="http://blog.unijimpe.net/validar-formularios-con-mootools/">Validar Formularios con Mootools</a> o también <a href="http://blog.unijimpe.net/vanadium-validar-formularios-facilmente/">Vanadium: Validar formularios fácilmente</a>). La segunda forma es hacerlo con PHP verificando que los datos no estén vacíos, asignando valores por defecto si es que el campo esta vacío, entre otras verificaciones.</p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/php-con-mysql-insertar-datos-en-mysql/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>PHP con MySQL: Introducción a SQL</title><link>http://blog.unijimpe.net/php-con-mysql-introduccion-a-sql/</link> <comments>http://blog.unijimpe.net/php-con-mysql-introduccion-a-sql/#comments</comments> <pubDate>Sun, 05 Dec 2010 19:11:40 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[navicat]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[phpmyadmin]]></category> <category><![CDATA[sql]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1250</guid> <description><![CDATA[<p><strong>SQL</strong> (<em>Structured query language</em>) es el lenguaje para interactuar con las bases de datos, el cual nos permitirá insertar registros, actualizar registros, buscar registros así como manipular tablas.</p><p>El lenguaje SQL es semejante en &#8230;</p>]]></description> <content:encoded><![CDATA[<p><strong>SQL</strong> (<em>Structured query language</em>) es el lenguaje para interactuar con las bases de datos, el cual nos permitirá insertar registros, actualizar registros, buscar registros así como manipular tablas.</p><p>El lenguaje SQL es semejante en todos los servidores de base de datos salvo pequeñas diferencias, en nuestro caso veremos una guía de SQL para MySQL. Los ejemplos los puedes probar directamente en la línea de comandos de MySQL o en algún cliente como <a href="http://www.phpmyadmin.net">phpMyAdmin</a> o <a href="http://www.navicat.com/">Navicat</a>.</p><p><strong>Preparando los datos</strong></p><p>Para nuestro ejemplo imaginemos que necesitamos almacenar los datos de una empresa. Para cada empresa necesitamos guardar: nombre, dirección, teléfono y una imagen con su logo. Entonces necesitaremos crear una tabla a la que llamaremos '<em>empresa</em>' la cual tendrá 5 campos:</p><ul><li><strong>id</strong>: será el identificador (interno) de la empresa el cual será un número entero.</li><li><strong>nombre</strong>: es el campo que aceptará una cadena de texto con el nombre de la empresa.</li><li><strong>direccion</strong>: campo que guardará una cadena de texto con la dirección de la empresa.</li><li><strong>telefono</strong>: es un campo que aceptará solo números que representan el teléfono de la empresa.</li><li><strong>imagen</strong>: es el campo donde guardaremos el nombre del archivo del logo de la empresa.</li></ul><h3>Crear tablas con SQL</h3><p>Para definir la estructura de la tabla utilizaremos <strong>CREATE TABLE</strong>, donde se asigna el nombre de la tabla así como cada uno de los campos indicando que tipos de datos vamos a almacenar. Entre los principales tipos de datos disponibles tenemos:</p><ul><li><strong>int</strong>: que permite guardar números enteros.</li><li><strong>float</strong>: permite almacenar datos decimales.</li><li><strong>date</strong>: para guardar fechas, el formato de la fecha es <em>aaaa-mm-dd</em>.</li><li><strong>datetime</strong>: es para guardar fecha y hora, el formato es <em>aaaa-mm-dd hh:mm:ss</em>.</li><li><strong>time</strong>: para almacenar la hora, el formato de la hora es <em>hh:mm:ss</em>.</li><li><strong>char(n)</strong>: almacena una cadena de texto de longitud fija <strong>n</strong> (De 0 a 255 caracteres).</li><li><strong>varchar(n)</strong>: para cadenas de tamaño variable de hasta <strong>n</strong> caracteres (De 0 a 255).</li><li><strong>text</strong> es un campo para almacenar textos de hasta 65535 caracteres.</li></ul><p>Para nuestro ejemplo crearíamos la tabla con 5 campos, donde el primero de ellos será el identificador de la empresa que será un entero que ser irá auto-incrementando.</p><div class="syntax_hilite"><div id="sql-63"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">CREATE</span> <span style="color: #993333;">TABLE</span> empresa <span style="color:#006600;">&#40;</span></div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp;id int<span style="color:#006600;">&#40;</span><span style="color: #cc66cc;color:#800000;">11</span><span style="color:#006600;">&#41;</span> <span style="color: #993333;">NOT</span> <span style="color: #993333;">NULL</span> <span style="color: #993333;">AUTO_INCREMENT</span>,</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp;nombre varchar<span style="color:#006600;">&#40;</span><span style="color: #cc66cc;color:#800000;">180</span><span style="color:#006600;">&#41;</span>,</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp;direccion varchar<span style="color:#006600;">&#40;</span><span style="color: #cc66cc;color:#800000;">180</span><span style="color:#006600;">&#41;</span>,</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp;telefono int<span style="color:#006600;">&#40;</span><span style="color: #cc66cc;color:#800000;">8</span><span style="color:#006600;">&#41;</span>,</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp;imagen varchar<span style="color:#006600;">&#40;</span><span style="color: #cc66cc;color:#800000;">50</span><span style="color:#006600;">&#41;</span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#006600;">&#41;</span></div></li></ol></div></div></div><p></p><p>Notese que por cada campo definimos el tipo de dato que puede almacenar. Los campos nombre y dirección aceptan textos de hasta 180 caracteres mientras que el campo imagen solo acepta 50 caracteres como máximo.</p><h3>Insertar datos con SQL</h3><p>Para insertar datos en las tablas haremos uso de la sentencia <strong>INSERT INTO</strong>, para ello podemos indicar los campos con sus respectivos valores, esto respetando los tipos de datos aceptados.</p><p>Para nuestra tabla recién creada, insertaremos registros de la siguiente forma:</p><div class="syntax_hilite"><div id="sql-64"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">INSERT</span> <span style="color: #993333;">INTO</span> empresa <span style="color:#006600;">&#40;</span>nombre, direccion, telefono, imagen<span style="color:#006600;">&#41;</span></div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">VALUES</span> <span style="color:#006600;">&#40;</span><span style="color: #ff0000;">'Apple'</span>, <span style="color: #ff0000;">'1 Infinite Loop, Cupertino'</span>, <span style="color: #cc66cc;color:#800000;">89961010</span>, <span style="color: #ff0000;">'apple.png'</span><span style="color:#006600;">&#41;</span></div></li></ol></div></div></div><p></p><p>Como se aprecia no es necesario incluir el dato para el <em>id</em> por el del tipo AUTO_INCREMENT lo cual significa que se creará automáticamente y con un valor incrementado en 1 al anterior registro.</p><p>Si estamos insertando todos los valores de una tabla, podríamos obviar los nombres de los campos si mantenemos el mismo orden en el que fueron creados los campos.</p><div class="syntax_hilite"><div id="sql-65"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">INSERT</span> <span style="color: #993333;">INTO</span> empresa</div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">VALUES</span> <span style="color:#006600;">&#40;</span><span style="color: #ff0000;">'Apple'</span>, <span style="color: #ff0000;">'1 Infinite Loop, Cupertino'</span>, <span style="color: #cc66cc;color:#800000;">89961010</span>, <span style="color: #ff0000;">'apple.png'</span><span style="color:#006600;">&#41;</span></div></li></ol></div></div></div><p></p><p>También se pueden insertar solo algunos campos de la tabla y no necesariamente en el orden en que fueron creados los campos en donde si debemos indicar los nombres de los campos, por ejemplo:</p><div class="syntax_hilite"><div id="sql-66"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">INSERT</span> <span style="color: #993333;">INTO</span> empresa <span style="color:#006600;">&#40;</span>nombre, logo<span style="color:#006600;">&#41;</span></div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">VALUES</span> <span style="color:#006600;">&#40;</span><span style="color: #ff0000;">'Apple'</span>, <span style="color: #ff0000;">'apple.png'</span><span style="color:#006600;">&#41;</span></div></li></ol></div></div></div><p></p><p>Los campos para los que no asignamos valores tendrán valores nulos o el valor por defecto que hayamos definido en la creación de la tabla.</p><h3>Editar datos con SQL</h3><p>Para actualizar datos de los registros de una tabla se puede utilizar <strong>UPDATE</strong>, donde indicamos la tabla donde se harán los cambios, los campos a reemplazar con sus respectivos valores asi como la condición que se debe cumplir para realizar el cambio de los datos.</p><p>Para hacer uso de estas condiciones, MySQL provee de funciones de comparación como:</p><ul><li><strong>=</strong> para comparar si dos valores son iguales.</li><li><strong>&lt;&gt;</strong> para comparar si dos valores son diferentes.</li><li><strong>!=</strong> para comparar si dos valores son diferentes. Igual al operador &lt;&gt;.</li><li><strong>&lt;=</strong> compara si un dato es menor o igual a otro.</li><li><strong>&lt;</strong> verifica si el datos es menor a otro.</li><li><strong>=&gt;</strong> para compara si el datos es mayor o igual a otro.</li><li><strong>&gt;</strong> prueba si el datos es mayor a otro.</li><li><strong>IS NULL</strong> devuelve verdadero si el campo es nulo.</li><li><strong>IS NOT NULL</strong> verdadero si el campo no es nulo.</li></ul><p>Adicionalmente se pueden utilizar las funciones booleanas como <strong>NOT</strong>, <strong>AND</strong>, <strong>OR</strong> y <strong>XOR</strong>.</p><p>Continuando con nuestro ejemplo, suponiendo que tenemos registrada una empresa con el identificador 57, podríamos actualizar los datos de la siguiente forma:</p><div class="syntax_hilite"><div id="sql-67"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">UPDATE</span> empresa</div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">SET</span> nombre = <span style="color: #ff0000;">'Google'</span>, direccion = <span style="color: #ff0000;">'1600 Amphitheatre Parkway, Mountain View'</span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">WHERE</span> id = <span style="color: #cc66cc;color:#800000;">57</span></div></li></ol></div></div></div><p></p><p>También podríamos asignar una imagen por defecto a todas las empresas que no tengan logo, para ello haríamos:</p><div class="syntax_hilite"><div id="sql-68"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">UPDATE</span> empresa</div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">SET</span> imagen = <span style="color: #ff0000;">'logo-default.png'</span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">WHERE</span> imagen <span style="color: #993333;">IS</span> <span style="color: #993333;">NULL</span></div></li></ol></div></div></div><p></p><h3>Eliminar datos con SQL</h3><p>Para eliminar datos utilizaremos <strong>DELETE FROM</strong>, en esta sentencia indicamos sobre que tabla vamos a realizar la eliminación además de la condición que se debe cumplir para realizar la eliminación.</p><p>En nuestro ejemplo eliminaremos todas las empresas que tengan el campo del nombre vacio o nulo.</p><div class="syntax_hilite"><div id="sql-69"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">DELETE</span> <span style="color: #993333;">FROM</span> empresa</div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">WHERE</span> nombre <span style="color: #993333;">IS</span> <span style="color: #993333;">NULL</span> <span style="color: #993333;">OR</span> nombre = <span style="color: #ff0000;">''</span></div></li></ol></div></div></div><p></p><h3>Consultar datos con SQL</h3><p>Para consultar datos (extraer datos) de una tabla se utiliza <strong>SELECT</strong> indicando los campos que deseamos extraer y el nombre de la tabla que utilizaremos.</p><p>Para nuestra tabla de ejemplo si deseamos consultar todas nombres y direcciones de las empresas:</p><div class="syntax_hilite"><div id="sql-70"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> nombre, direccion <span style="color: #993333;">FROM</span> empresa</div></li></ol></div></div></div><p></p><p>Se pueden utilizar alias para los campos extraídos, por ejemplo:</p><div class="syntax_hilite"><div id="sql-71"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> nombre <span style="color: #993333;">AS</span> <span style="color: #ff0000;">'Empresa'</span>, direccion <span style="color: #993333;">AS</span> <span style="color: #ff0000;">'Dirección'</span> <span style="color: #993333;">FROM</span> empresa</div></li></ol></div></div></div><p></p><p>Si deseamos extraer todos los campos podemos utilizar el caracter <strong>*</strong>.</p><div class="syntax_hilite"><div id="sql-72"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa</div></li></ol></div></div></div><p></p><p><strong>Filtrando los resultados</strong></p><p>Podemos aplicar condiciones a nuestras consultas con la directiva <strong>WHERE</strong>.</p><p>Para extraer la empresa con identificador 57 la consulta sería:</p><div class="syntax_hilite"><div id="sql-73"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">WHERE</span> id = <span style="color: #cc66cc;color:#800000;">57</span></div></li></ol></div></div></div><p></p><p>Si deseamos mostrar todas las empresas que tengan registradas su dirección:</p><div class="syntax_hilite"><div id="sql-74"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">WHERE</span> direccion <span style="color: #993333;">IS</span> <span style="color: #993333;">NOT</span> <span style="color: #993333;">NULL</span></div></li></ol></div></div></div><p></p><p>Tambiém podriamos consultar todas las empresas cuyo nombre empiece con la letra A.</p><div class="syntax_hilite"><div id="sql-75"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">WHERE</span> nombre <span style="color: #993333;">LIKE</span> <span style="color: #ff0000;">'A%'</span></div></li></ol></div></div></div><p></p><p><strong>Ordenando los resultados</strong></p><p>Para el ordenamiento de los resultados se utiliza <strong>ORDER BY</strong>, este define por que campo se hará el ordenamiento así como si será en forma ascendente (ASC) o descendente (ASC).</p><p>Si utilizamos nuestra tabla de ejemplo podríamos listar todas las empresas en orden alfabetico:</p><div class="syntax_hilite"><div id="sql-76"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">ORDER</span> <span style="color: #993333;">BY</span> nombre <span style="color: #993333;">ASC</span></div></li></ol></div></div></div><p></p><p><strong>Contando los resultados</strong></p><p>Es posible contar los registros utilizando <strong>COUNT</strong>, esto unido al filtro de datos es útil para hacer conteos de datos.</p><p>Si deseamos conocer cuantas empresa registradas tenemos:</p><div class="syntax_hilite"><div id="sql-77"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> COUNT<span style="color:#006600;">&#40;</span>*<span style="color:#006600;">&#41;</span> <span style="color: #993333;">FROM</span> empresa</div></li></ol></div></div></div><p></p><p>Podríamos conocer cuantas empresas tienen registradas direcciones vacías:</p><div class="syntax_hilite"><div id="sql-78"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> COUNT<span style="color:#006600;">&#40;</span>*<span style="color:#006600;">&#41;</span> <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">WHERE</span> direccion = <span style="color: #ff0000;">''</span></div></li></ol></div></div></div><p></p><p><strong>Limitando los resultados</strong></p><p>MySQL permite limitar la cantidad de resultados utilizando la palabra LIMIT, esta sentencia es muy flexible pues permite definir a partir de que registro y la cantidad de datos devueltos.</p><p>Si deseamos visualir las 5 ultimas empresas registradas en nuestra tabla tendríamos:</p><div class="syntax_hilite"><div id="sql-79"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">ORDER</span> <span style="color: #993333;">BY</span> id <span style="color: #993333;">DESC</span> <span style="color: #993333;">LIMIT</span> <span style="color: #cc66cc;color:#800000;">5</span></div></li></ol></div></div></div><p></p><p>Si estamos mostrando los resultados ordenados alfabeticamente en grupos de 10, tendríamos:</p><div class="syntax_hilite"><div id="sql-80"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #808080; font-style: italic;">/* Para mostrar los primero 10 resultados */</span></div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">ORDER</span> <span style="color: #993333;">BY</span> nombre <span style="color: #993333;">ASC</span> <span style="color: #993333;">LIMIT</span> <span style="color: #993333;">LIMIT</span> <span style="color: #cc66cc;color:#800000;">0</span>, <span style="color: #cc66cc;color:#800000;">10</span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #808080; font-style: italic;">/* Para mostrar los siguientes 10 resultados */</span></div></li><li style="color:#26536A;"><div style=""><span style="color: #993333;">SELECT</span> * <span style="color: #993333;">FROM</span> empresa <span style="color: #993333;">ORDER</span> <span style="color: #993333;">BY</span> nombre <span style="color: #993333;">ASC</span> <span style="color: #993333;">LIMIT</span> <span style="color: #993333;">LIMIT</span> <span style="color: #cc66cc;color:#800000;">10</span>, <span style="color: #cc66cc;color:#800000;">10</span></div></li></ol></div></div></div><p></p><p>Ahora ya podemos crear, editar, eliminar y consultar los datos utilizando condiciones con la posibilidad de filtrar, ordenar y limitar los resultados.</p><p><strong>Mas Información</strong></p><p>Obviamente este artículo es solo un resumen del lenguaje SQL, donde he seleccionado las sentencias mas utilizadas en la manipulación de datos. Para una guía completa y detallada pueden visitar la documentación oficial de MySQL o en algún libro que explique con mayor detalle estos temas.</p><ul><li><a href="http://dev.mysql.com/doc/refman/5.0/es/tutorial.html">MySQL 5.0 Reference Manual :: Curso (tutorial) de MySQL</a></li><li><a href="http://dev.mysql.com/doc/refman/5.0/es/sql-syntax.html">MySQL 5.0 Reference Manual :: Sintaxis de sentencias SQL</a></li><li><a href="http://dev.mysql.com/doc/refman/5.0/es/column-types.html">MySQL 5.0 Reference Manual :: Tipos de columna</a></li><li><a href="http://dev.mysql.com/doc/refman/5.0/es/comparison-operators.html">MySQL 5.0 Reference Manual :: Funciones y operadores de comparación</a></li></ul><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/php-con-mysql-introduccion-a-sql/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>PHP con MySQL: Crear una conexión a MySQL</title><link>http://blog.unijimpe.net/php-con-mysql-crear-una-conexion-a-mysql/</link> <comments>http://blog.unijimpe.net/php-con-mysql-crear-una-conexion-a-mysql/#comments</comments> <pubDate>Mon, 29 Nov 2010 05:12:25 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[base de datos]]></category> <category><![CDATA[conexion]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1248</guid> <description><![CDATA[<p>La conexión de PHP con MySQL es el primer paso para crear aplicaciones web. Al tener una conexión podremos insertar, editar y consultar registros de una Base de Datos lo cual nos permitirá crear aplicaciones que &#8230;</p>]]></description> <content:encoded><![CDATA[<p>La conexión de PHP con MySQL es el primer paso para crear aplicaciones web. Al tener una conexión podremos insertar, editar y consultar registros de una Base de Datos lo cual nos permitirá crear aplicaciones que permitan a los visitantes a consultar información de acuerdo a sus necesidades.</p><p><strong>Crear una conexión con MySQL</strong></p><p>Para crear una conexión con MySQL hacemos uso de la función <em>mysql_connect</em> y luego definimos la base de datos que vamos a utilizar por medio de la función <em>mysql_select_db</em>.</p><div class="syntax_hilite"><div id="php-84"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$conexion</span> = <a href="http://www.php.net/mysql_connect"><span style="color:#000066;">mysql_connect</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"localhost"</span>, <span style="color:#FF0000;">"usuario"</span>, <span style="color:#FF0000;">"clave"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><a href="http://www.php.net/mysql_select_db"><span style="color:#000066;">mysql_select_db</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"demo"</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li></ol></div></div></div><p></p><p>En la primera línea hemos creado la conexión a un servidor local y luego hemos seleccionado la base de datos <em>'demo'</em> la cual utilizaremos para consultar datos según nuestras necesidades.</p><p><strong>Explicando la Conexión</strong></p><p>En el ejemplo hemos utilizado la función <em>mysql_connect</em>, el cual recibe tres parámetros.</p><div class="syntax_hilite"><div id="code-85"><div class="code"><ol><li style="color:#3A6A8B;"><div style="">mysql_connect<span style="color:#006600;">&#40;</span><span style="color:#CC0000;">"server"</span>, <span style="color:#CC0000;">"username"</span>, <span style="color:#CC0000;">"password"</span><span style="color:#006600;">&#41;</span></div></li></ol></div></div></div><p></p><p>Donde se tienen:</p><ul><li><strong>server</strong>: es la dirección IP o el nombre del servidor de base de datos.</li><li><strong>username</strong>: nombre usuario para acceder a MySQL.</li><li><strong>password</strong>: clave de acceso a MySQL.</li></ul><p><strong>Cerrando la Conexión</strong></p><p>Una vez creada la conexión y hecho las consultas necesarias a nuestra base de datos, es necesario cerrar esa conexión de esta forma liberamos recursos del servidor y mejoramos el rendimiento de nuestra aplicación.</p><div class="syntax_hilite"><div id="php-86"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><a href="http://www.php.net/mysql_close"><span style="color:#000066;">mysql_close</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li></ol></div></div></div><p></p><p>Para cerrar la conexión hemos utilizado la función mysql_close que recibe como parámetro el identificador de la conexión.</p><p><strong>Recomendaciones</strong></p><ul><li>Se recomienda hacer la conexión en un archivo externo, para poder utilizarlo en diferentes páginas. De esta forma si cambiamos de servidor solo editamos el archivo de conexión con los nuevos datos de conexión.</li><li>Es recomendable cerrar siempre las conexiones, esto previene que la aplicación tenga errores por exceso de conexiones.</li></ul><p>Este post forma parte de una seria de artículos destinados a explicar el manejo de datos con MySQL. Poco a poco explicaremos como insertar registros, editar, eliminar y extraer datos de MySQL.</p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/php-con-mysql-crear-una-conexion-a-mysql/feed/</wfw:commentRss> <slash:comments>14</slash:comments> </item> <item><title>Hosting Gratuitos sin Publicidad</title><link>http://blog.unijimpe.net/hosting-gratuitos-sin-publicidad/</link> <comments>http://blog.unijimpe.net/hosting-gratuitos-sin-publicidad/#comments</comments> <pubDate>Mon, 05 Apr 2010 05:14:12 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[Servicios Web]]></category> <category><![CDATA[Tools]]></category> <category><![CDATA[cPanel]]></category> <category><![CDATA[email]]></category> <category><![CDATA[ftp]]></category> <category><![CDATA[gtatuito]]></category> <category><![CDATA[hosting]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1153</guid> <description><![CDATA[<p>El requisito indispensable para empezar con un web o blog es un hosting. Hay muchas opciones de pago, pero si estas aprendiendo o deseas experimentar un hosting gratuito será de mucha ayuda para empezar, ya cuando &#8230;</p>]]></description> <content:encoded><![CDATA[<p>El requisito indispensable para empezar con un web o blog es un hosting. Hay muchas opciones de pago, pero si estas aprendiendo o deseas experimentar un hosting gratuito será de mucha ayuda para empezar, ya cuando tengan cierta experiencia o cantidad de visitas darán el paso de mudarse a un hosting de pago.</p><p>Les presento una breve lista de hosting gratuitos libres de publicidad y con todas las características necesarias para empezar con su web.</p><p><strong>000WebHost</strong><br /> <a href="http://www.000webhost.com/"><img src="http://blog.unijimpe.net/wp-content/uploads/2010/04/000webhost.gif" alt="" title="000webhost" width="200" height="57" /></a></p><ul><li>1500 MB de espacio en disco.</li><li>100 GB de transferencia mensual.</li><li>PHP y MySQL (5 bases de datos).</li><li>Acceso mediante FTP.</li><li>Administración con cPanel.</li><li>Alojamiento de hasta 5 dominios.</li></ul><p><strong>110MB Hosting</strong><br /> <a href="http://www.110mb.com/"><img src="http://blog.unijimpe.net/wp-content/uploads/2010/04/110mb-hosting.gif" alt="" title="110mb-hosting" width="200" height="73" /></a></p><ul><li>110 MB de espacio en disco.</li><li>100 GB de transferencia mensual.</li><li>Soporte de PHP 4 y PHP 5.</li><li>Alojamineto hasta 1 dominio.</li></ul><p><strong>BlackAppleHost</strong><br /> <a href="http://www.blackapplehost.com/"><img src="http://blog.unijimpe.net/wp-content/uploads/2010/04/black-apple-host.png" alt="" title="black-apple-host" width="200" height="60" /></a></p><ul><li>5 GB de espacio.</li><li>20 GB de transferencia mensual.</li><li>Máximo 2 dominio.</li><li>Administración mediante LayeredPanel.</li><li>Soporte de PHP y base de datos MySQL.</li><li>1 Cuenta de FTP.</li></ul><p><strong>Byet Internet</strong><br /> <a href="http://byethost.com/free-hosting"><img src="http://blog.unijimpe.net/wp-content/uploads/2010/04/byte-host.gif" alt="" title="byte-host" width="200" height="48" /></a></p><ul><li>5500 MB de espacio.</li><li>200 GB de transferencia mensual.</li><li>Soporte de PHP y Bases de datos MySQL.</li><li>Alojamiento hasta de 50 dominios.</li><li>Cuentas de FTP e Email.</li><li>Administración con VistaPanel</li></ul><p>Además estos mismos proveedores ofrecen servicios de hosting pagados con mejores características y mayor soporte a los cuales puedes migrarse fácilmente.</p><p>Si conocen algún otro sitio que ofrezca hosting gratuito de calidad pueden compartirlo con nuestros visitantes dejando un comentario con las características del servicio. También si tienen alguna queja sobre estos pueden comentarlo para que otras personas se eviten problemas.</p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/hosting-gratuitos-sin-publicidad/feed/</wfw:commentRss> <slash:comments>36</slash:comments> </item> <item><title>Kissa: acortar URLs con PHP</title><link>http://blog.unijimpe.net/kissa-acortar-urls-con-php/</link> <comments>http://blog.unijimpe.net/kissa-acortar-urls-con-php/#comments</comments> <pubDate>Tue, 28 Apr 2009 04:05:49 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[Servicios Web]]></category> <category><![CDATA[API]]></category> <category><![CDATA[Google]]></category> <category><![CDATA[gratuito]]></category> <category><![CDATA[PNG]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1025</guid> <description><![CDATA[<p><a href="http://kissa.be">Kissa.be</a> es un servicio gratuito de acortamiento de enlaces al estilo de <a href="http://tinyurl.com/">TinyURL</a>, pero entre las cualidades que destacan  son un API para crear URL dinámicamente e incluso puedes descargar el código fuente para iniciar &#8230;</p>]]></description> <content:encoded><![CDATA[<p><a href="http://kissa.be">Kissa.be</a> es un servicio gratuito de acortamiento de enlaces al estilo de <a href="http://tinyurl.com/">TinyURL</a>, pero entre las cualidades que destacan  son un API para crear URL dinámicamente e incluso puedes descargar el código fuente para iniciar tu propio de servicio de acortamiento de URLs.</p><p style="text-align:center;"><img src="http://blog.unijimpe.net/wp-content/uploads/2009/04/kissa-logo-mini.png" alt="kissa-logo-mini" title="kissa-logo-mini" width="143" height="89" /></p><p>Este servicio además del tradicional acortamiento del URL te brinda un API con el cual se le puede envíar el URL para acortar y te devolverá el resultado, podemos hacer uso de este API  mediante el url:</p><p><a href="http://kissa.be/api/shortener/url?content=http://google.com">http://kissa.be/api/shortener/url?content=http://google.com</a></p><p>Este URL devolverá un texto con el resultado del acortamiento solicitado. Para mayor información acerca del API pueden visitar <a href="http://kissa.be/api">Kissa.be API</a>.</p><p>Finalmente si quieres iniciar tu propio servicio de acortamiento de URLs puedes descargar el script completo en <a href="http://code.google.com/p/kissabe/">http://code.google.com/p/kissabe/</a>, este script requiere para su funcionamiento PHP, MySQL y acceso al archivo .<em>htaccess</em> para crear las URLs personalizadas.</p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/kissa-acortar-urls-con-php/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Insertar registros en MySQL</title><link>http://blog.unijimpe.net/insertar-registros-en-mysql/</link> <comments>http://blog.unijimpe.net/insertar-registros-en-mysql/#comments</comments> <pubDate>Mon, 30 Mar 2009 14:49:39 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=1007</guid> <description><![CDATA[<p>En un articulo anterior <a href="http://blog.unijimpe.net/conectar-php-con-mysql/">Conectar PHP con MySQL</a> explicamos como realizar una conexión a MySQL y obtener datos con PHP, en esta ocasión veremos como insertar registros en nuestra base de datos.</p><p style="text-align:center;"></p><p><strong>Creando la Base de </strong>&#8230;</p>]]></description> <content:encoded><![CDATA[<p>En un articulo anterior <a href="http://blog.unijimpe.net/conectar-php-con-mysql/">Conectar PHP con MySQL</a> explicamos como realizar una conexión a MySQL y obtener datos con PHP, en esta ocasión veremos como insertar registros en nuestra base de datos.</p><p style="text-align:center;"><img src="http://blog.unijimpe.net/wp-content/uploads/2009/03/insert-mysql.gif" alt="insert-mysql" title="insert-mysql" width="345" height="177" /></p><p><strong>Creando la Base de datos</strong><br /> Para este ejemplo necesitamos una base de datos que la llamaremos <em>demo</em>, en la cual crearemos un tabla llamada <em>empresa</em> la cual tendrá los siguientes campos: <em>idemp</em>, <em>nombre</em>, <em>direccion</em>, <em>telefono</em>. Para los menos experimentados les dejo el <a href="http://samples.unijimpe.net/demo.sql">script SQL</a> para crear esta tabla.</p><p><strong>Sintaxis SQL para insertar registros</strong><br /> Lo primero que necesitamos conocer el la sintaxis SQL para insertar registros la cual mostramos a continuación en donde table es la <em>tabla</em> donde deseamos insertar los datos, <em>field1</em> y <em>field2</em> son los nombres de los campos y <em>value1</em> y <em>value2</em> los valores:</p><div class="syntax_hilite"><div id="sql-92"><div class="sql"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #993333;">INSERT</span> <span style="color: #993333;">INTO</span> <span style="color: #993333;">TABLE</span> <span style="color:#006600;">&#40;</span>field1, field2<span style="color:#006600;">&#41;</span> <span style="color: #993333;">VALUES</span> <span style="color:#006600;">&#40;</span>value1, value2<span style="color:#006600;">&#41;</span></div></li></ol></div></div></div><p></p><p>Luego, para hacer la inserción utilizando PHP, lo primero es crear una conexión y luego enviar la consulta utilizando el método <em>mysql_query</em> de la siguiente forma:</p><div class="syntax_hilite"><div id="php-93"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$conexion</span> = <a href="http://www.php.net/mysql_connect"><span style="color:#000066;">mysql_connect</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"localhost"</span>, <span style="color:#FF0000;">"usuario"</span>, <span style="color:#FF0000;">"clave"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style=""><a href="http://www.php.net/mysql_select_db"><span style="color:#000066;">mysql_select_db</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"demo"</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$que</span> = <span style="color:#FF0000;">"INSERT INTO empresa (nombre, direccion, telefono) "</span>;</div></li><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$que</span>.= <span style="color:#FF0000;">"VALUES ('Inka Tours', 'Av Pardo 728', '511 4845858') "</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#0000FF;">$res</span> = <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$que</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span> or <a href="http://www.php.net/die"><span style="color:#000066;">die</span></a><span style="color:#006600;">&#40;</span><a href="http://www.php.net/mysql_error"><span style="color:#000066;">mysql_error</span></a><span style="color:#006600;">&#40;</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span>;</div></li></ol></div></div></div><p></p><p><strong>Creando el Formulario</strong><br /> Para que el usuario puede ingresar los datos de manera sencilla crearemos un formulario en cual cual se ingresarán los datos de la empresa, para ello creamos el formulario en html.</p><div class="syntax_hilite"><div id="html-94"><div class="html"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/form.html"><span style="color: #000000;">&lt;form</span></a> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">"insertar"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"insertar"</span> <span style="color: #000066;">method</span>=<span style="color: #ff0000;">"post"</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">""</span><span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">Nombre:</div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"nombre"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">"nombre"</span> <span style="color: #000066;">size</span>=<span style="color: #ff0000;">"50"</span> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">Direccion:</div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"dir"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">"dir"</span> <span style="color: #000066;">size</span>=<span style="color: #ff0000;">"50"</span> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style="">Telefono:</div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"fono"</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"text"</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">"fono"</span> <span style="color: #000066;">size</span>=<span style="color: #ff0000;">"50"</span> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"submit"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"Submit"</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">"Insertar Registro"</span> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/input.html"><span style="color: #000000;">&lt;input</span></a> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">"hidden"</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">"action"</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">"add"</span> /<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;/form&gt;</span></span></div></li></ol></div></div></div><p></p><p>Notese que hemos agregado un campo oculto llamado <em>action</em> el cual lo utilizaremos para verificar si se ha enviado el formulario y procesar los datos. Entonces verificamos que se enviado el formulario en cuyo caso realizamos la conexión a MySQL y enviamos la consulta para insertar los datos.</p><div class="syntax_hilite"><div id="php-95"><div class="php"><ol><li style="color:#3A6A8B;"><div style=""><span style="color:#0000FF;">$state</span> = <span style="color:#000000;">false</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#616100;">if</span> <span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'action'</span><span style="color:#006600;">&#93;</span> == <span style="color:#FF0000;">"add"</span><span style="color:#006600;">&#41;</span> <span style="color:#006600;">&#123;</span></div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$conexion</span> = <a href="http://www.php.net/mysql_connect"><span style="color:#000066;">mysql_connect</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"localhost"</span>, <span style="color:#FF0000;">"usuario"</span>, <span style="color:#FF0000;">"clave"</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <a href="http://www.php.net/mysql_select_db"><span style="color:#000066;">mysql_select_db</span></a><span style="color:#006600;">&#40;</span><span style="color:#FF0000;">"demo"</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$que</span> = <span style="color:#FF0000;">"INSERT INTO empresa (nombre, direccion, telefono) "</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$que</span>.= <span style="color:#FF0000;">"VALUES ('"</span>.<span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'nombre'</span><span style="color:#006600;">&#93;</span>.<span style="color:#FF0000;">"', '"</span>.<span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'dir'</span><span style="color:#006600;">&#93;</span>.<span style="color:#FF0000;">"', '"</span>.<span style="color:#0000FF;">$_POST</span><span style="color:#006600;">&#91;</span><span style="color:#FF0000;">'fono'</span><span style="color:#006600;">&#93;</span>.<span style="color:#FF0000;">"') "</span>;</div></li><li style="color:#26536A;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$res</span> = <a href="http://www.php.net/mysql_query"><span style="color:#000066;">mysql_query</span></a><span style="color:#006600;">&#40;</span><span style="color:#0000FF;">$que</span>, <span style="color:#0000FF;">$conexion</span><span style="color:#006600;">&#41;</span> or <a href="http://www.php.net/die"><span style="color:#000066;">die</span></a><span style="color:#006600;">&#40;</span><a href="http://www.php.net/mysql_error"><span style="color:#000066;">mysql_error</span></a><span style="color:#006600;">&#40;</span><span style="color:#006600;">&#41;</span><span style="color:#006600;">&#41;</span>;</div></li><li style="color:#3A6A8B;"><div style="">&nbsp; &nbsp; <span style="color:#0000FF;">$state</span> = <span style="color:#000000;">true</span>;</div></li><li style="color:#26536A;"><div style=""><span style="color:#006600;">&#125;</span></div></li></ol></div></div></div><p></p><p>Finalmente mostramos un mensaje cuando se ha insertado correctamente el registro en la base de datos.</p><div class="syntax_hilite"><div id="html-96"><div class="html"><ol><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php if <span style="color: #66cc66;">&#40;</span>$state<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> ?<span style="color: #000000;">&gt;</span></a></span></div></li><li style="color:#26536A;"><div style=""><span style="color: #009900;"><a href="http://december.com/html/4/element/p.html"><span style="color: #000000;">&lt;p&gt;</span></a></span><span style="color: #009900;"><a href="http://december.com/html/4/element/em.html"><span style="color: #000000;">&lt;em&gt;</span></a></span>Registro insertado correctamente<span style="color: #009900;"><span style="color: #000000;">&lt;/em&gt;</span></span><span style="color: #009900;"><span style="color: #000000;">&lt;/p&gt;</span></span></div></li><li style="color:#3A6A8B;"><div style=""><span style="color: #009900;"><span style="color: #000000;">&lt;</span></a>?php <span style="color: #66cc66;">&#125;</span> ?<span style="color: #000000;">&gt;</span></a></span></div></li></ol></div></div></div><p></p><p><strong>Observaciones</strong><br /> Por motivos de facilitar el entendimiento del funcionamiento de la inserción de datos hemos obviado algunos puntos. Pero es necesario advertir que para insertar registros los datos que vienen desde formularios nunca deben ir directamente a la consulta pues pueden contener sentencias SQL (Esto es llamado <strong>Inyección SQL</strong>) proceso mediante el cual pueden ingresar a nuestros sistemas y manipular datos sin consentimiento nuestro.</p><p>Otro punto que hay que tener en cuenta es validar los datos, esto para prevenir que se ingrese texto donde debería haber números por ejemplo, lo cual generaría errores de SQL.</p><p>Finalmente les dejo los archivos fuente para que lo descarguen y hagan sus propias pruebas para comprender el funcionamiento de este script.</p><p style="text-align:left;"><a href="http://blog.unijimpe.net/download/insert-mysql.zip" title="Insert data MySQL"><img src="http://blog.unijimpe.net/btdown.png" border="0"></a></p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/insertar-registros-en-mysql/feed/</wfw:commentRss> <slash:comments>62</slash:comments> </item> <item><title>SQLyog: Cliente MySQL</title><link>http://blog.unijimpe.net/sqlyog-cliente-mysql/</link> <comments>http://blog.unijimpe.net/sqlyog-cliente-mysql/#comments</comments> <pubDate>Mon, 11 Sep 2006 10:40:08 +0000</pubDate> <dc:creator>unijimpe</dc:creator> <category><![CDATA[General]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[gratis]]></category> <category><![CDATA[navicat]]></category> <category><![CDATA[PHP]]></category><guid isPermaLink="false">http://blog.unijimpe.net/?p=117</guid> <description><![CDATA[<p><a href="http://www.webyog.com/en/">SQLyog</a> un cliente para Bases de datos MySQL sobre Windows, es una muy buena alternativa para los que se sienten de manos atadas con <a href="http://www.phpmyadmin.com">phpMyAdmin</a> o <a href="http://www.mysqlfront.de/">MySQLFront </a>.</p><p style="text-align:center"></p><p>SQLyog tiene dos versiones:</p><strong>Community&#8230;</strong> la cual es]]></description> <content:encoded><![CDATA[<p><a href="http://www.webyog.com/en/">SQLyog</a> un cliente para Bases de datos MySQL sobre Windows, es una muy buena alternativa para los que se sienten de manos atadas con <a href="http://www.phpmyadmin.com">phpMyAdmin</a> o <a href="http://www.mysqlfront.de/">MySQLFront </a>.</p><p style="text-align:center"><img id="image118" alt=conn_mngr.jpg src="http://blog.unijimpe.net/wp-content/uploads/2006/09/conn_mngr.jpg" /></p><p>SQLyog tiene dos versiones:</p><ul><li><strong>Community</strong> la cual es gratis siempre y cuando sea para uso privado.</li><li><strong>Enterprise</strong> con un precio de 47 dolares para uso comercial.</li></ul><p>Estas dos versiones tienen pequeñas diferencias, las cuales no afectan a las partes funcionales del programa. Este programa presenta multiples opciones que te permiten administrar tu bases de datos, usuarios, exportar e importar datos en multiples formatos.</p><p style="text-align:center"><img id="image121" alt=table_create_alter.jpg src="http://blog.unijimpe.net/wp-content/uploads/2006/09/table_create_alter.jpg" /></p><p>Desde luego que no se compara a <a href="http://www.navicat.com">Navicat</a>, pues <strong>Navicat </strong>presenta opciones mucho mas completas y la interfaz es mucho mas elaborada. Pero a diferencia de Navicat, <strong>SQLyog</strong> tiene la versión gratuita.</p><p style="text-align:center"><img id="image120" alt=main_data_tab.jpg src="http://blog.unijimpe.net/wp-content/uploads/2006/09/main_data_tab.jpg" /></p><p style="text-align:center"><img id="image119" alt=db_copy.jpg src="http://blog.unijimpe.net/wp-content/uploads/2006/09/db_copy.jpg" /></p><p style="font-size: 10px;border-top: 1px solid #666666;margin-top=12px;padding-top:6px;">&copy; 2006 - 2011 <a href="http://blog.unijimpe.net">unijimpe</a> - Utiliza este feed solo para uso personal, partes de este feed pueden ser utilizados mencionando al autor, no esta permitido publicar enteramente este feed para uso comercial sin permiso del autor.</p><br /> ]]></content:encoded> <wfw:commentRss>http://blog.unijimpe.net/sqlyog-cliente-mysql/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced (User agent is rejected)
Database Caching using disk: basic

Served from: blog.unijimpe.net @ 2012-02-08 10:11:40 -->
