Translate mysql_query to PDO "UPDATE * SET ... WHERE ..."

0

Hello, I recently started translating my sites to PDO for obvious reasons. However this is giving me a bit of a headache.

$sql = mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("banco") or die(mysql_error());

$id1 = $_GET['id'];
$lat1 = $_GET['lat'];
$lon1 = $_GET['lon'];
$info1 = $_GET['info'];
date_default_timezone_set('America/Sao_Paulo');
$hora1 = date('Y-m-d H:i');

$sql = mysql_query("UPDATE tabela SET lat='$lat1', lon='$lon1', info='$info1', hora='$hora1' WHERE id='$id1'");
    header ("Location: painel.php");

This code is relatively simple, however I can not translate it. If anyone can help me, thank you.

    
asked by anonymous 14.06.2017 / 15:21

2 answers

1

To connect to the database and select it:

$sql = new PDO('mysql:host=localhost;dbname=banco', "user", "pass");

To execute the query:

sql->query(UPDATE tabela SET lat='$lat1', lon='$lon1', info='$info1', hora='$hora1' WHERE id='$id1');
    
14.06.2017 / 15:30
0

To establish a connection to a database using PDO it is necessary to define the connection string and pass it to a PDO instance, as exemplified below:

$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "banco";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // modo de erro do PDO para gerações de exceções
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "UPDATE tabela SET lat='$lat1', lon='$lon1', info='$info1', hora='$hora1' WHERE id='$id1'";

    $stmt = $conn->prepare($sql);

    // executa a query
    $stmt->execute();

    // mensagem de sucesso
    echo $stmt->rowCount() . " records UPDATED successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;

In the definition of the connection string with that database, you must first define the type of the database (in this case MySQL), the data for authentication in the database (user and pass), in addition to the database to which you want to establish a connection (in this case "bank"). In the presented script, the PDO error mode was also defined for exception generations whenever any errors occur with the executions of queries in the database.

Whenever a script is terminated, the connection is automatically terminated. If you need to terminate the connection before, just use the following statement: $conn = null;

    
14.06.2017 / 16:19