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

Asked

Viewed 261 times

0

Hello, I recently started translating my sites to PDO for obvious reasons. Yet this one 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 am not able to translate it. If anyone can help me, I’d appreciate it.

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');

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 shown 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, one must initially define the type of the database (in this case, Mysql), the data for authentication in the database (user and pass), and the database to which one wishes to establish connection (in this case "database"). In the shown script, the PDO error mode has also been set for generations of exceptions whenever any errors occur with the executions of queries in the database.

Whenever a script is finished, the connection is automatically terminated. If you need to finish the connection first, just use the following instruction: $conn = null;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.