How can I troubleshoot further? I have 3 styles of querying. This is for a fetchType = 'single' ( single row that is) and a populated parameterArray
public function query($fetchType, $queryType, $parameterArray=null)
{
$query=$this->sql_array[$queryType];
if($parameterArray==null)
{
$pdoStatement = $this->db_one->query($query);
$results = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$this->db_one->quote($query);
$pdoStatement = $this->db_one->prepare($query);
$results = $pdoStatement->execute($parameterArray);
if($fetchType=='single')
{
$results = $pdoStatement->fetch(PDO::FETCH_ASSOC);
}
else if($fetchType=='multiple')
{
$results = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
}
return $results;
}
My results is coming back false and I see no data in the sql table.
I verified that the queryType exists in the lookup table and that other queries are working.
Here is the actual query. I inserted new lines to make readable.
"signup_insert" =>
"INSERT INTO credentials
(h_token, h_file, h_pass, email, name, picture, privacy)
VALUES (?, ?, ?, ?, ?, ?, ?)"
Here is the debug code I created:
$pipe['debug_h_token']=$h_token;
$pipe['debug_h_file']=$h_file;
$pipe['debug_h_pass']=$h_pass;
$pipe['debug_email']=$this->TO->get('email');
$pipe['debug_name']=$this->TO->get('name');
$pipe['debug_picture']=$picture;
$pipe['debug_privacy']=$privacy;
$test = $this->DBO->query('single', 'signup_insert', array(
$h_token,
$h_file,
$h_pass,
$this->TO->get('email'),
$this->TO->get('name'),
$picture,
$privacy
));
$pipe['debug_test'] = $test;
Related
I'm trying to execute a SQL query that saves POST data into the database. The data comes in correctly, and the arrays that are coming with the POST data are converted to strings.
When the query gets executed the message 'Succesfully saved into database' appears, however the data isn't visible in the database, so there must be a little mistake inside my code, however I can't seem to find it.
See my code below:
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
mysqli_stmt_execute($stmt);
echo '<p>Succesfully saved into database</p>';
exit();
}
}
This is how the database looks like
Thanks in advance!
You should not assume that the query ran successfully because an exception was not thrown. You need to consider what the function returns and how many rows are affected before knowing if it ran successfully or not. Update your code to this and figure out what is going on:
Also check to make sure you are not just updating the same row over and over.
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
if ( mysqli_stmt_execute($stmt) ) {
echo '<p>Succesfully saved into database</p>';
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt) );
}
}
mysqli_stmt_close($stmt);
}
I have the following in my PHP.
$stmt = $conn->prepare("INSERT IGNORE INTO savesearch (user, searchedFor, sortOrder, buildURLString, aspectFilters, oneSignalId, totalEntries)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $user, $searchedFor, $sortOrder, $buildURLString, $aspectFilters, $oneSignalId, $totalEntries);
// set parameters and execute
$user = $_POST['user'];
$searchedFor = $_POST["searchedFor"];
$sortOrder = $_POST["sortOrder"];
$buildURLString = $_POST["buildURLString"];
$aspectFilters = $_POST["aspectFilters"];
$oneSignalId = $_POST["oneSignalId"];
$totalEntries = $_POST["totalEntries"];
if ($stmt->execute()) {
$output->success = true;
echo json_encode($output);
} else {
$error->error = mysqli_error($conn);
echo json_encode($error);
}
However, IGNORE is not being picked up, it continues to add entries. Is there another good way to fix this?
Id like to see if the USER and the URL is the same, dont add, echo duplicate entry.
IGNORE is actually mostly for the opposite of what you want here. Instead, you can amend your MySQL table something like:
ALTER TABLE savesearch ADD UNIQUE KEY(user, buildURLString)
Then remove your IGNORE keyword
I'm trying to figure out how to use sql transactions with mysqli prepared statements. I haven't been able to find any examples that use multiple prepared statements (that aren't OO), so I'm not really sure how to use transactions with them.
This is the closest I could figure:
mysqli_autocommit($database, FALSE);
$transferq = 'INSERT INTO money (user_id, bank, onhand, type, amount, source) VALUES (?, ?, ?, ?, ?, ?)';
$transferstmt = mysqli_stmt_init($database);
mysqli_stmt_prepare($transferstmt, $transferq);
mysqli_stmt_bind_param($transferstmt, 'iiisis', $userid, $newbank, $newmoney, $type, $amount, $source);
mysqli_stmt_execute($transferstmt);
$insertq = 'UPDATE users SET money=?, bank=? WHERE user_id=' . $userid . ' LIMIT 1';
$insertstmt = mysqli_stmt_init($database);
mysqli_stmt_prepare($insertstmt, $insertq);
mysqli_stmt_bind_param($insertstmt, 'ii', $newmoney, $newbank);
mysqli_stmt_execute($insertstmt);
mysqli_commit($database);
But, I have no idea if that would even work. My biggest issue, though, is I'm not sure how to check if the queries failed or not (and therefore whether or not to commit). I saw an example that I think did something like
if(mysqli_stmt_execute($stmt)){
mysqli_commit($database);
}else{
mysqli_rollback($database);
}
But I can't really do that since I have multiple prepared statements to execute.
How is this supposed to work?
Maybe I did not understand your question, but what about this?
mysqli_autocommit($database, FALSE);
$transferq = 'INSERT INTO money (user_id, bank, onhand, type, amount, source) VALUES (?, ?, ?, ?, ?, ?)';
$transferstmt = mysqli_stmt_init($database);
mysqli_stmt_prepare($transferstmt, $transferq);
mysqli_stmt_bind_param($transferstmt, 'iiisis', $userid, $newbank, $newmoney, $type, $amount, $source);
if (not mysqli_stmt_execute($transferstmt) ){
mysqli_rollback($database);
return;
}
$insertq = 'UPDATE users SET money=?, bank=? WHERE user_id=' . $userid . ' LIMIT 1';
$insertstmt = mysqli_stmt_init($database);
mysqli_stmt_prepare($insertstmt, $insertq);
mysqli_stmt_bind_param($insertstmt, 'ii', $newmoney, $newbank);
if (not mysqli_stmt_execute($insertstmt) ){
mysqli_rollback($database);
return;
}
mysqli_commit($database);
The next level if form of this object-oriented using of mysqli or PDO (without transactions, as example of way of work with database):
class my_database{
private static $inner_link_to_driver;
protected static function factory( ){
if (not static::$inner_link_to_driver){
static::$inner_link_to_driver = new ...(USER, SERVER, PASSWD, PORT);
}
return static::$inner_link_to_driver;
}
public static function do_something($params, &$message ){
$query = "...";
$stmt = static::factory()->prepare($query);
if (not $stmp ){
$message = 'Error prepare query '.$query.PHP_EOL.static::factory()-> ..(get_error);
return FALSE;
}
if (not $stmt->execute($params) ){
$message = 'Error execute query '.$query.PHP_EOL.static::factory()-> ..(get_error);
return FALSE;
}
return TRUE;
}
}
public function save(User $user_object)
{
$data = array();
$data[] = $user_object->username;
$data[] = $user_object->email;
$data[] = $user_object->password;
if (is_null($user_object->id)) {
$data[] = $user_object->salt;
$data[] = time();
$sth = $this->db->prepare("INSERT INTO users (username, email, password, salt, created) VALUES (?, ?, ?, ?, ?)");
$sth->execute($data);
} else {
//Update User
}
}
As you can see if there is no id there will be an insert if there is an ID however, there will be a update.. However I am not sure how the UPDATE statement in PDO will look like, I want to push in all data that is in the array where the ID = $user_object->id.
There is no "UPDATE statement in PDO". There is just usual SQL UPDATE query. PDO does not have it's own SQL. it is just an API to send SQL query to the DB server.
So, just write usual SQL with placeholders
UPDATE users SET username=?, email=?, password=?, salt=? WHERE id=?
I was wondering if someone could help me.
Im trying to integrate some code into my application, the code that i need to integrate is written with PDO statements and i have no idea how it goes.
I was wondering if someone could help me convert it.
The code is as follows
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
$stmt = $PDO->prepare($sql);
$stmt->execute($args);
if (empty($mid)) {
$mid = $PDO->lastInsertId();
}
$insertSql = "insert into message2_recips values ";
$holders = array();
$params = array();
foreach ($rows as $row) {
$holders[] = "(?, ?, ?, ?)";
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
$insertSql .= implode(',', $holders);
$stmt = $PDO->prepare($insertSql);
$stmt->execute($params);
You shoudl use PDO unles for some technical reason you cant. If you dont know it, learn it. Maybe this will get you started:
/*
This the actual SQL query the "?" will be replaced with the values, and escaped accordingly
- ie. you dont need to use the equiv of mysql_real_escape_string - its going to do it
autmatically
*/
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
// these are the values that will replace the ?
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
// create a prepared statement object
$stmt = $PDO->prepare($sql);
// execute the statement with $args passed in to be used in place of the ?
// so the final query looks something like:
// insert into message2 (mid, seq, created_on_ip, created_by, body) values ($mid, $seq, 1.2.2.1, $currentUser, $body)
$stmt->execute($args);
if (empty($mid)) {
// $mid id is the value of the primary key for the last insert
$mid = $PDO->lastInsertId();
}
// create the first part of another query
$insertSql = "insert into message2_recips values ";
// an array for placeholders - ie. ? in the unprepared sql string
$holders = array();
// array for the params we will pass in as values to be substituted for the ?
$params = array();
// im not sure what the $rows are, but it looks like what we will do is loop
// over a recordset of related rows and do additional inserts based upon them
foreach ($rows as $row) {
// add a place holder string for this row
$holders[] = "(?, ?, ?, ?)";
// assign params
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
// modify the query string to have additional place holders
// so if we have 3 rows the query will look like this:
// insert into message2_recips values (?, ?, ?, ?),(?, ?, ?, ?),(?, ?, ?, ?)
$insertSql .= implode(',', $holders);
// create a prepared statment
$stmt = $PDO->prepare($insertSql);
// execute the statement with the params
$stmt->execute($params);
PDO really is better. It has the same functionality as MySQLi but with a consistent interface across DB drivers (ie. as long as your SQL is compliant with a different database you can theoretically use the exact same php code with mysql, sqlite, postresql, etc.) AND much better parameter binding for prepared statements. Since you shouldnt be using the mysql extension any way, and MySQLi is more cumbersome to work with than PDO its really a no-brainer unless you specifically have to support an older version of PHP.