How to insert POST data into MySQL via Form through Xenforo with SQL Injection Prevention

calnet

Member
Hey Everyone,

I'm new to Xenforo after moving away from phpBB and love it!
However, I am just transferring over my customized pages across and struggling to find an answer to this question. I have searched everywhere high and low for an example but to no avail cant find a solution which I hope one of you will help. (This may sound like a dumb question as it's probably something easy to do)

The question is:
How to insert POST data into MySQL via Form through Xenforo with SQL Injection Prevention

For example, I have created a seperate table for the user data (e.g xf_mytablename) and have created a form on Xenforo, once a user hits the submit button, it gets posted to the next page. On the next page I have the users data, and insert it like this:

PHP:
$usersdata = $_POST["usersdata"];

$db = XenForo_Application::get('db');

$db->query("INSERT INTO xf_mytablename (user_id,userdata)
               VALUES ('$userid','$usersdata');");

The question is, what is the proper way of doing this?
This works but is susceptible to SQL injection attacks..etc
I've been pondering for hours trying numerous prepared statements, mysqli real escapes and it just refuses to work.

Kind Regards,
 
The database adapter already supports prepared statements. It's probably easiest to look at any of the model classes. They'll show you a few examples using it.
 
Hey Mike,

Thanks for your reply, would you be able to point me in the direction of the path or location where I can find these model classes?
Like I mentioned, I am new to Xenforo completely and even a sample snippet code of a prepared statement in xenforo would help greatly.

I tried using one of the web like:
PHP:
// prepare and bind
$stmt = $db->prepare("INSERT INTO xf_mytablename (user_id, description) VALUES (userid, ?)");
$stmt->bind_param("s", $userdata);

// set parameters and execute

$userdata= "Julie";
$stmt->execute();
echo "New records created successfully";

Instead, I just get:
Fatal Error: Call to undefined method Zend_Db_Statement_Mysqli::bind_param()

Kind Regards,
 
PHP:
$stmt = $db->prepare("INSERT INTO xf_mytablename (user_id, description) VALUES (userid, ?)");
$stmt->bind_param("s", $userdata);
Would be
PHP:
$stmt = $db->query("INSERT INTO xf_mytablename (user_id, description) VALUES (userid, ?)", array($userdata));

What he meant by look at the model classes was to look in /library/XenForo/Model/ at all the php files to see how queries are executed.

Also, you could use the insert function rather than the query function. Look at Zend Framework v1's documentation for the database layers.
 
Top Bottom