0
votes

I am a newbie in ModX, trying to insert to database but always failed. This is my insert script :

<?php
define('MODX_CORE_PATH', '/aocore/');
define('MODX_CONFIG_KEY','config');
require_once MODX_CORE_PATH . 'model/modx/modx.class.php';

$host = 'localhost';
$username = 'asdsadsada';
$password = 'dsadsadsada';
$dbname = 'sadsadsadsadas';
$port = 3306;
$charset = 'utf8';

$dsn = "mysql:host=$host;dbname=$dbname;port=$port;charset=$charset";
$xpdo = new xPDO($dsn, $username, $password);
 echo $o = ($xpdo->connect()) ? 'Connected' : 'Not Connected';
$results = $xpdo->query("insert into table_name (name,email) VALUES ('".$_POST['name'].",".$_POST['email']."')"); 
$stmt = $modx->prepare($results);
$stmt->execute();
?>

Please help, totally stuck here.

Thanks

2

2 Answers

0
votes

Without seeing much of your database structure let alone any error log info it's very hard to debug/test your code because we can't reproduce anything.

By the looks of it you are not using objects. You may want to concider using your own schema and inserting the given records as objects in the DB. Have a look at this guide for more information on creating custom database tables in MODX.

Please make sure you're sanitizing the input that is being saved into the database with functions such as strip_tags() and htmlspecialchars() in order to prevent XSS and other injection attacks. Also make sure you are using prepared statements.

By looking at the code however i can see that you are executing the query() function which is meant for querying the database (retreiving database records). If you want to execute SQL statements such as "INSERT" you will need to use the exec() function.

Example:

$xpdo->exec("INSERT INTO `table_name` (`name`,`email`) VALUES ('".htmlspecialchars(strip_tags($_POST['name'])).",".htmlspecialchars(strip_tags($_POST['email']))."')");

If you are not going to be using MODX objects you may find it easier to use PHP's PDO interface with prepared statements.

0
votes

Well, if it is not too late. You didn't share the exact problem but I see something strange in your code:

...VALUES ('".$_POST['name'].",".$_POST['email']."')");

If the values from POST array get into the string, you have

...VALUES ('John,[email protected]')");

John,[email protected]' is a single value where as there should be two values for name and email. So, try to put ' inside your query like

...VALUES ('".$_POST['name']."','".$_POST['email']."')");