5

I have a WordPress theme, and I'm trying to save data from an HTML form into a database.

I made the HTML form and added a "save & close" button which calls a JavaScript function named saveData() that takes the data from the form and sends it to addrow.php, which should save the data into a database table named vel.

I think the problem is in addrow.php because in WordPress, one needs to use the global $wpdb or some other thing.

What would be a simple example be for how to save data from an HTML form into a database table in a WordPress-powered application?

The addrow.php code:

<?php
    require("phpsqlinfo_dbinfo.php");

    // Gets data from URL parameters
    $nombre = $_GET['nombre'];
    $direccion = $_GET['direccion'];
    $lat = $_GET['lat'];
    $lng = $_GET['lng'];
    $tipo = $_GET['tipo'];

    // Opens a connection to a MySQL server
    $connection = mysql_connect ("localhost", $username, $password);
    if (!$connection) {
        die('Not connected : ' . mysql_error());
    }

    // Set the active MySQL database
    $db_selected = mysql_select_db($database, $connection);
    if (!$db_selected) {
        die ('Can\'t use db : ' . mysql_error());
    }

    // Insert new row with user data
    $query = sprintf("INSERT INTO vel " .
    " (id, nombre, direccion, lat, lng, tipo ) " .
    " VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
    mysql_real_escape_string($nombre),
    mysql_real_escape_string($direccion),
    mysql_real_escape_string($lat),
    mysql_real_escape_string($lng),
    mysql_real_escape_string($tipo));

    $result = mysql_query($query);

    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }
?>

1 Answer 1

8

You are correct; in order to insert data into a database table, it is a best practice to use $wpdb. The WordPress Codex can provide you with examples and more information to help you proceed.

For example, to insert a new record into a database table, you can do this (from the above linked page):

$wpdb->insert( 'table', array( 'column1' => 'value1', 'column2' => 123 ), array( '%s', '%d' ) )

If you post additional code (e.g., how does addrow.php currently try to save the data?), we might be able to provide more specific information.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.