/** * @param PDO $link * @param string $user * @param string $field1 * @param string $field2 * @param string $lang * @param string $group * @param string $id1 * @param string $id2 * @param string $word * @param int $type */ function update($link, $user, $field1, $field2, $lang, $group, $id1, $id2, $word, $type) { $sql = "SELECT associd FROM `associations` WHERE id1 = :id1 AND id2 = :id2 AND word = :word AND user = :user AND assigned_group = :group AND lang = :lang AND type = :type"; $stmt = $link->prepare($sql); $stmt->bindValue(':id1', $id1, PDO::PARAM_STR); $stmt->bindValue(':id2', $id2, PDO::PARAM_STR); $stmt->bindValue(':word', $word, PDO::PARAM_STR); $stmt->bindValue(':type', $type, PDO::PARAM_INT); $stmt->bindValue(':user', $user, PDO::PARAM_STR); $stmt->bindValue(':group', $group, PDO::PARAM_STR); $stmt->bindValue(':lang', $lang, PDO::PARAM_STR); if ($stmt->execute() === false) { error_log(var_export($link->errorInfo(), true)); die("Error performing database operation."); } if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $sql = "INSERT INTO `evaluations` ( associd , evaluator , vote , popvote ) values ( :associd , :user , :vote , :popvote )"; $stmt = $link->prepare($sql); $stmt->bindValue(':associd', $row['associd'], PDO::PARAM_STR); $stmt->bindValue(':user', $_SESSION['user_array']['user'], PDO::PARAM_STR); $stmt->bindValue(':vote', $field1 === 'upvotes' ? 2 : ($field1 === 'neutralvotes' ? 1 : 0), PDO::PARAM_INT); $stmt->bindValue(':popvote', $field2 === 'popupvotes' ? 2 : ($field2 === 'popneutralvotes' ? 1 : 0), PDO::PARAM_INT); if ($stmt->execute() === false) { error_log(var_export($link->errorInfo(), true)); die("Error performing database operation."); } } }
/** * Prepare and execute a query. * * If the query fails, output a diagnostic message * @param string $query * Query to run * @return bool */ public function do_query($query) { // echo "do_query($query)\n"; // $stmt = $this->pdo->query( $query, PDO::FETCH_ASSOC ); // echo "PDO returned"; // var_dump($stmt); $string = preg_replace("/^#[^\n]*\$/m", "\n", $query); $string = preg_replace("/^(--[^-]).*/m", "\n", $string); $queries = preg_split('/;\\s*$/m', $string); foreach ($queries as $query) { $query = trim($query); if (!empty($query)) { $result = $this->pdo->query($query); if ($this->pdo->errorCode() == 0) { continue; } else { var_dump($result); var_dump($this->pdo->errorInfo()); // die( "Cannot execute $query: " . $this->pdo->errorInfo() ); } } } /******* * if ( $this->pdo->errorCode() == 0 ) { * //echo "returning the PDOStmt\n"; * return $stmt; * } * * // operation failed, so output description of where and why * $errorInfo = $this->pdo->errorInfo(); * echo "Oops, can't do query:\n {$query}\n in " * . basename( __FILE__) . " line " . __LINE__.":\n " * . $errorInfo[0] . ": " . $errorInfo[2] . "\n Call stack:\n"; * $backtrace = debug_backtrace(); * $dir_name = dirname( __FILE__ ); * $cwd_len = strlen( $dir_name ) + 1; * foreach ($backtrace as $frame ) { * echo " "; * if ( array_key_exists( 'class', $frame ) ) { * echo " class {$frame['class']}"; * if ( array_key_exists( 'function', $frame ) ) { * echo " method {$frame['function']}"; * } * } * else { * if ( array_key_exists( 'function', $frame ) ) { * echo " function {$frame['function']}"; * } * } * if ( array_key_exists( 'file', $frame ) ) { * echo " file ". substr( $frame['file'], $cwd_len ); * } * if ( array_key_exists( 'line', $frame ) ) { * echo " line {$frame['line']}"; * } * echo "\n"; * } ******/ return TRUE; }
/** * {@inheritdoc} */ public function query($query, $resultsetType = Resultset::TYPE_ARRAY) { try { //$query = "select * from product"; $stmt = $this->resource->prepare($query); if ($stmt === false) { $error = $this->resource->errorInfo(); throw new Exception\InvalidArgumentException($error[2]); } if (!$stmt->execute()) { throw new Exception\InvalidArgumentException('Statement could not be executed (' . implode(' - ', $this->resource->errorInfo()) . ')'); } $results = new Resultset($resultsetType); if ($stmt->columnCount() > 0) { while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $results->append($row); } } $stmt->closeCursor(); } catch (Exception\InvalidArgumentException $e) { throw $e; } catch (\Exception $e) { $eclass = get_class($e); $msg = "GenericPdo '{$eclass}' : {$e->getMessage()} [{$query}]"; throw new Exception\InvalidArgumentException($msg); } return $results; }
private function _error_handler($errtext, $errline) { $err = sprintf('%s on line %d.', $errtext, $errline); if (defined('DEBUG') && DEBUG) { $err .= sprintf(PHP_EOL . "Description: %s", print_r($this->con->errorInfo(), true)); } throw new RuntimeException($err); }
/** * Get the latest error message from the DB driver * * @return string */ public function get_error_message() { $error = $this->dbh->errorInfo(); if (isset($error[2])) { return $error[2]; } return ''; }
private function initDb() { $this->pdo = new \PDO($this->dns, $this->user, $this->pass, $this->options); if ($this->pdo == false) { throw new \Exception(var_export($this->pdo->errorInfo(), true)); } $this->optionsChanged = false; }
public function DoLastError() { if ($this->connection) { $pdoErrorInfo = $this->connection->errorInfo(); return $pdoErrorInfo[2]; } else { return $this->connectionError; } }
/** * @param string $fixture * * @throws \InvalidArgumentException */ public function loadFixture($fixture) { if (!is_file(__DIR__ . "/fixtures/{$fixture}.sql")) { throw new \InvalidArgumentException("The asked fixture file {$fixture}.sql does not exists"); } $success = $this->getConnection()->exec(file_get_contents(__DIR__ . "/fixtures/{$fixture}.sql")); if ($success === false) { $this->fail("Error with {$fixture} fixtures : {$this->connection->errorInfo()[2]}"); } }
/** * Generate PDO error * * @param string $sql * @param \PDOStatement $statement * @return \PDOException */ protected function error($sql, \PDOStatement $statement = null) { $error = $this->pdo->errorInfo(); if (!$error[1] and $statement) { $error = $statement->errorInfo(); $statement->closeCursor(); unset($statement); } $code = is_int($error[0]) ? $error[0] : null; return new \PDOException('[' . $error[0] . '] ' . $error[2] . ', in query (' . $sql . ')', $code); }
/** * @return Member[] */ public function getMembers() { $statement = $this->pdo->query('SELECT * FROM members'); if (false === $statement) { throw new \PDOException(join("\n", $this->pdo->errorInfo()), $this->pdo->errorCode()); } $members = []; while ($row = $statement->fetch(\PDO::FETCH_OBJ)) { $members[] = $this->rowToMember($row); } return $members; }
public function run(SqlFile $file) { $statement = $this->pdo->prepare($file->getContents()); try { $result = $statement->execute(); if ($result === false) { throw new \Exception("Query Returned " . var_export($this->pdo->errorInfo(), true)); } } catch (\Exception $e) { throw new MigrationException("Running SQL File " . $file->getFile()->getPathname() . " failed.", $e); } finally { $statement->closeCursor(); } }
/** * Internal function to execute PDO queries when the * query option is set to a PDO object * @param string $query The SQL query to execute * @param array $parameters Parameters to bind to the query * @return array */ function executePdoQuery($query, $parameters) { $stmt = $this->dbh->prepare($query); if (!$stmt) { echo "Error in preparing query: " . $this->dbh->errorCode() . " " . htmlentities(print_r($this->dbh->errorInfo(), true)) . " " . htmlentities($query); exit; } $res = $stmt->execute($parameters); if (!$res) { echo "Error in executing query: " . $stmt->errorCode() . " " . htmlentities(print_r($stmt->errorInfo(), true)) . " " . htmlentities($query); exit; } return $stmt->fetchAll(\PDO::FETCH_ASSOC); }
function open_db() { // Try to open the db itself. If that fails, try to create it. $dbFile = SUPPORT_DIR . DIRECTORY_SEPARATOR . "jobs.sqlite"; $pdo = new PDO("sqlite:{$dbFile}", null, null); if (!$pdo) { throw new DbException($pdo->errorInfo(), "Error opening (or creating) " . $dbFile); } $stmt = 'CREATE TABLE IF NOT EXISTS ' . TABLE_NAME . ' (jobId TEXT, username TEXT, filename TEXT, when_added INTEGER, PRIMARY KEY (jobId))'; // SQLite doesn't have a specific date type. We're using integer seconds (Unix time) if ($pdo->exec($stmt) === false) { throw new DbException($pdo->errorInfo(), 'Error creating ' . TABLE_NAME . ' table'); } return $pdo; }
/** * 执行一条sql语句 * 返回数组或者bool * * @param $sql * @return array|bool */ public function query($sql) { $dbh = $this->dbh; $this->_beforeQuery($sql); $ps = $dbh->query($sql); $error_info = $this->dbh->errorInfo(); if ($error_info[2] != null) { throw new Exception("Excute Sql Error: " . $error_info[2]); } if (is_bool($ps)) { return $ps; } $obj = $ps->fetchAll(PDO::FETCH_ASSOC); return $obj; }
/** * @param string $cmd Sql SAFE query to execute. * @param array $bind Array of parameters to bind. * @throws \PDOException * @return \PDOStatement */ public function execute($cmd, array $bind = []) { if (is_null($this->pdo)) { $this->openConnection(); } $statement = $this->pdo->prepare($cmd); if (!$statement) { throw MySqlException::create($this->pdo->errorInfo()); } $result = $statement->execute($bind); if (!$result) { throw MySqlException::create($statement->errorInfo()); } return $statement; }
public function errorInfo() { if ($this->pdo == null) { return null; } return $this->pdo->errorInfo(); }
function query() { $sql = func_get_arg(0); $parameters = array_slice(func_get_args(), 1); // try to connect to database static $handle; if (!isset($handle)) { try { // connect to database $handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER . ";charset=utf8", USERNAME, PASSWORD); // ensure that PDO::prepare returns false when passed invalid SQL $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch (Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); exit; } } $statement = $handle->prepare($sql); if ($statement === false) { trigger_error($handle->errorInfo()[2], E_USER_ERROR); exit; } $results = $statement->execute($parameters); // return result set's rows, if any if ($results !== false) { return $statement->fetchAll(PDO::FETCH_ASSOC); } else { return false; } }
/** * Run a query and return the resulting statement * @param string $sql * @param array $params * @throws \Exception * @return \PDOStatement */ public function query($sql, $params = null) { $stmt = $this->pdo->prepare($sql); $startTime = 0; if ($this->isProfiling()) { $startTime = microtime(true); } // Execute and check if there was an error if ($stmt) { if ($stmt->execute($params)) { if ($this->isProfiling()) { $executionTime = microtime(true) - $startTime; $this->profilingData[] = ['time' => $executionTime, 'sql' => $sql]; } return $stmt; } else { $errorInfo = $stmt->errorInfo(); } } else { $errorInfo = $this->pdo->errorInfo(); } $errorMessage = "Query failed - SQLSTATE[{$errorInfo[0]}]"; if (isset($errorInfo[1])) { $errorMessage .= " ({$errorInfo[1]}: {$errorInfo[2]})"; } $errorMessage .= "; SQL: \"{$sql}\""; throw new \Exception($errorMessage); }
function insert_db() { try { // connect $db = new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // insert $stmt = $db->prepare("insert into gps (head1, head2, id, utctime, accuracy, latitude, lat_dir, longitude, lon_dir, speed, compass, utcdate, checksum) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $array = split(",|\\*", get_latest_shipdata()); $array[3] = preg_replace('/(\\d{2})(\\d{2})(\\d{2})/', '$1:$2:$3', $array[3]); $array[11] = preg_replace('/(\\d{2})(\\d{2})(\\d{2})/', '20$3-$2-$1', $array[11]); // select $stmt = $db->query('select * from gps order by line desc limit 1'); if (!$stmt) { $info = $db->errorInfo(); exit($info[2]); } while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { #echo '<p>' . $data['line'] . ':' . $data['id'] . "</p>\n"; if ($data['utctime'] == $array[3]) { exit; } } // insert execute $stmt->execute($array); echo "inserted " . $db->lastInsertId(); // disconnect $db->null; } catch (PDOException $e) { echo $e->getMessage(); exit; } }
public function execute($statement) { Ac::timerStart(); $this->connect(); list($_this, $statement) = Ac::trigger(__CLASS__ . "_before_" . __FUNCTION__, array($this, trim($statement))); $this->last_row_count = 0; $this->beginTransaction(); $this->last_row_count = $this->pdo->exec($statement); if ($this->last_row_count > 0) { $this->clearCache(); } $this->num_operations++; if (!$this->isError()) { $this->commit(); $status = "success"; if ($this->getConfig("log_success")) { $this->log($statement, "OK", null); } } else { $this->rollback(); $status = "error"; if ($this->getConfig("log_errors")) { $this->log($statement, $this->pdo->errorInfo(), null); } } Ac::trigger(__CLASS__ . "_on_" . __FUNCTION__, array($this, $statement, $status, $this->last_row_count)); return $this->last_row_count; }
public function exec($statement) { if (isset($this->dsn) and stristr($this->dsn, 'anjuke_db') and preg_match('/\\sajk_propertys\\s/i', $statement)) { if (stristr($statement, 'select CITYID') or stristr($statement, 'insert') or stristr($statement, 'update ')) { } else { $dir = '/home/www/logs/propsql'; if (!is_dir($dir)) { mkdir($dir, 0755, true); $content = '-=-=-=-=-=-=-=-=-=-=' . PHP_EOL; $content .= 'DSN: ' . $this->dsn . PHP_EOL; $content .= 'URI: ' . $_SERVER['REQUEST_URI'] . PHP_EOL; $content .= 'JOB: ' . var_export($_SERVER['argv'], true) . PHP_EOL; $content .= 'SQL: ' . $statement . PHP_EOL; file_put_contents($dir . '/' . date('Ymd'), $content, FILE_APPEND); } } } if (APF::get_instance()->is_debug_enabled()) { APF::get_instance()->debug(__CLASS__ . '[' . $this->name . ']' . "->exec: {$statement}"); } $logger = APF::get_instance()->get_logger(); $logger->debug(__CLASS__, '[' . $this->name . ']->exec: ', $statement); $stmt = parent::exec($statement); if ($stmt instanceof PDOStatement) { $stmt->setFetchMode($this->default_fetch_mode); } else { $error_info = parent::errorInfo(); if (parent::errorCode() !== '00000') { throw new APF_Exception_SqlException(parent::errorCode(), $this->get_name() . ' | ' . $this->config['dsn'] . ' | ' . $statement . ' | ' . join(' | ', $error_info)); } } return $stmt; }
public function CreateClientDataBase($db_name) { $createdb_result = 0; /*$db_prefix = Configurator::getInstance()->getSettings( "db_prefix" ); if( $db_prefix == 'not' ){ $database = $db_name; }else{ $database = $db_prefix.'_'.$db_name; }*/ $host = Configurator::getInstance()->getSettings("database_host_full"); $root = Configurator::getInstance()->getSettings("database_user_full"); $root_password = Configurator::getInstance()->getSettings("database_password_full"); $user = Configurator::getInstance()->getSettings("database_user_full"); $db = $db_name; try { $dbh = new PDO("mysql:host={$host}", $root, $root_password); $dbh->exec("CREATE DATABASE `{$db}`;\r\n\t\t\t\t\tGRANT ALL ON `{$db}`.* TO '{$user}'@'{$host}';\r\n\t\t\t\t\tFLUSH PRIVILEGES;") or die(print_r($dbh->errorInfo(), true)); $createdb_result = 1; } catch (PDOException $e) { die("DB ERROR: " . $e->getMessage()); } $this->CopyTemplateDataBaseToClientDataBase($db_name); return $createdb_result; }
/** * @return Meetup[] */ public function getMeetups() { $statement = $this->pdo->query('SELECT m.*, count(r.member_identifier) as taken FROM meetups m LEFT JOIN rsvps r ON (r.meetup_identifier = m.identifier AND r.rsvp = "yes") GROUP BY m.identifier ORDER BY m.date ASC'); if (false === $statement) { throw new \PDOException(join("\n", $this->pdo->errorInfo()), $this->pdo->errorCode()); } $meetups = []; while ($row = $statement->fetch(\PDO::FETCH_OBJ)) { $meetups[] = $this->rowToMeetup($row); } return $meetups; }
function db() { static $pdo = false; global $MYSQL; if ($pdo !== false) { return $pdo; } if (!isset($MYSQL) || empty($MYSQL)) { return false; } if (!($pdo = new PDO('mysql:host=' . $MYSQL['host'] . ';dbname=' . $MYSQL['database'], $MYSQL['username'], $MYSQL['password']))) { list($err, $_, $info) = $pdo->errorInfo(); switch ($err) { case 1040: case 2002: $pdo = false; if ($_SERVER['REQUEST_METHOD'] == "GET") { die(header('HTTP/1.1 503 Service Unavailable') . "<html><head><meta http-equiv=refresh content=\"5 {$_SERVER['REQUEST_URI']}\"></head><body><table border=0 width=100% height=100%><tr><td><h3 align=center>" . _('The server load is very high at the moment. Retrying, please wait...') . "</h3></td></tr></table></body></html>"); } else { die(header('HTTP/1.1 503 Service Unavailable') . _("Too many users. Please press the Refresh button in your browser to retry.")); } default: $pdo = false; die(header('HTTP/1.1 503 Service Unavailable') . "[" . $err . "] dbconn: mysql_connect: " . $info); } } return $pdo; }
/** * @param $request * @return mixed|void */ public function getPackageRequest($request) { $this->resetResponse(); $this->addShopRequestCount(); $query = $this->db->query($request); if (!$query) { $errorInfo = $this->db->errorInfo(); $this->error = "Not a valid item package request! : " . $errorInfo[2]; return; } $response = $query->fetchAll(); if ($response) { $this->response = $response; } return parent::getPackageRequest($request); }
/** * WARNING: This function does not perform sanity check on the orderby clause! * To prevent SQL injection never use it without validating the clause first. * * $user and $input_language should also be checked to prevent access bypass * injections, since are used to compose the names of the tables to be queried. * * @param \PDO $link * @param string $user * @param string $input_language * @param string $orderby * @param int|null $id * @param int|null $type * @return bool|PDOStatement|null */ function get_test_results($link, $user, $input_language, $orderby, $id = null, $type = null) { if ($type !== null && $type == 1) { $sql = ''; } else { $sql = "SELECT \n resultid AS id\n , ttypeid +1 AS type\n , tresourceid\n , val AS word\n , lang\n , ROUND(\n (\n (\n IFNULL(orgfullvotes,0)\n + IFNULL(orghalfvotes,0) * 0.5\n + IFNULL(cohfullvotes,0)\n + IFNULL(cohhalfvotes,0) *0.5 \n )\n /\n IFNULL(\n NULLIF(\n IFNULL(orgfullvotes,0)\n + IFNULL(orgzerovotes,0)\n + IFNULL(orghalfvotes,0)\n + IFNULL(cohfullvotes,0)\n + IFNULL(cohzerovotes,0)\n + IFNULL(cohhalfvotes,0)\n , 0\n )\n , 1\n )\n ) * 10\n , 2\n ) AS allpointszerotenscale\n , ROUND(\n (\n (\n IFNULL(cohfullvotes,0)\n + IFNULL(cohhalfvotes,0) * 0.5 \n )\n /\n IFNULL(\n NULLIF(\n IFNULL(cohfullvotes,0)\n + IFNULL(cohzerovotes,0)\n + IFNULL(cohhalfvotes,0)\n ,0\n )\n , 1 \n )\n ) * 10\n , 2\n ) AS intpointszerotenscale\n , ROUND(\n (\n (\n IFNULL(orgfullvotes,0)\n + IFNULL(orghalfvotes,0) * 0.5 \n )\n /\n IFNULL(\n NULLIF(\n IFNULL(orgfullvotes,0)\n + IFNULL(orgzerovotes,0)\n + IFNULL(orghalfvotes,0)\n , 0\n )\n , 1\n )\n ) * 10\n , 2\n ) AS orgpointszerotenscale\n , firstedit\n , FROM_UNIXTIME(lastedit) AS time_stamp\n , orgfullvotes AS upvotes\n , orghalfvotes AS neutralvotes\n , orgzerovotes AS downvotes\n , cohfullvotes AS popupvotes\n , cohhalfvotes AS popneutralvotes\n , cohzerovotes AS popdownvotes\n FROM test_results WHERE user = :user AND lang = :lang " . ($id !== null ? ' AND resultid = :id ' : ''); } if ($type === null || $type == 1) { if ($sql !== '') { $sql .= " UNION ALL "; } $sql .= "SELECT \n did AS id\n , dgid + 1 AS type\n , NULL AS tresourceid\n , val AS word\n , lang\n , ROUND(\n (\n (\n IFNULL(orgfullvotes,0)\n + IFNULL(orghalfvotes,0) * 0.5\n + IFNULL(cohfullvotes,0)\n + IFNULL(cohhalfvotes,0) *0.5 \n )\n /\n IFNULL(\n NULLIF(\n IFNULL(orgfullvotes,0)\n + IFNULL(orgzerovotes,0)\n + IFNULL(orghalfvotes,0)\n + IFNULL(cohfullvotes,0)\n + IFNULL(cohzerovotes,0)\n + IFNULL(cohhalfvotes,0)\n , 0\n )\n , 1\n )\n ) * 10\n , 2\n ) AS allpointszerotenscale\n , ROUND(\n (\n (\n IFNULL(cohfullvotes,0)\n + IFNULL(cohhalfvotes,0) * 0.5\n )\n /\n IFNULL(\n NULLIF(\n IFNULL(cohfullvotes,0)\n + IFNULL(cohzerovotes,0)\n + IFNULL(cohhalfvotes,0)\n , 0\n )\n , 1\n )\n ) * 10\n , 2\n ) AS intpointszerotenscale\n , ROUND(\n (\n (\n IFNULL(orgfullvotes,0)\n + IFNULL(orghalfvotes,0) * 0.5\n )\n /\n IFNULL(\n NULLIF(\n IFNULL(orgfullvotes,0)\n + IFNULL(orgzerovotes,0)\n + IFNULL(orghalfvotes,0)\n , 0\n )\n , 1\n )\n ) * 10\n , 2\n ) AS orgpointszerotenscale\n , 'NULL' AS firstedit\n , 'NULL' AS time_stamp\n , orgfullvotes AS upvotes\n , orghalfvotes AS neutralvotes\n , orgzerovotes AS downvotes\n , cohfullvotes AS popupvotes\n , cohhalfvotes AS popneutralvotes\n , cohzerovotes AS popdownvotes\n FROM vditloid_results WHERE user = :useragain AND lang = :langagain " . ($id !== null ? ' AND did = :id ' : ''); } if (isset($orderby) && $orderby !== '') { $sql .= " ORDER BY {$orderby} "; } $stmt = $link->prepare($sql); if ($type === null || $type != 1) { $stmt->bindValue(':user', $user, PDO::PARAM_STR); $stmt->bindValue(':lang', $input_language, PDO::PARAM_STR); } if ($type === null || $type == 1) { $stmt->bindValue(':useragain', $user, PDO::PARAM_STR); $stmt->bindValue(':langagain', $input_language, PDO::PARAM_STR); } if ($id !== null) { $stmt->bindValue(':id', $id, PDO::PARAM_INT); } if ($stmt->execute() === false) { error_log(var_export($link->errorInfo(), true) . PHP_EOL . $sql); } return $stmt; }
/** * @param string $sql * @param array|null $placeholders * @param int $fetchStyle * * @return bool|array Returns false on an unexpected failure or the rows found by the statement. Returns an empty array when nothing is found */ public function select($sql, $placeholders = null, $fetchStyle = PDO::FETCH_ASSOC) { try { if (!($stmt = $this->_db->prepare($sql))) { $errorInfo = $this->_db->errorInfo(); throw new PDOException("Bind Error: " . $errorInfo[0] . " (" . $errorInfo[0] . ")", 0); } if (is_array($placeholders)) { foreach ($placeholders as $key => $placeholder) { if (is_int($key)) { $key++; } if (!$stmt->bindParam($key, $placeholders[$key])) { $errorInfo = $stmt->errorInfo(); throw new PDOException("Bind Error: " . $errorInfo[0] . " (" . $errorInfo[0] . ")", 0); } } } if (!$stmt->execute()) { $errorInfo = $stmt->errorInfo(); throw new PDOException("Execute Failed: " . $errorInfo[0] . " (" . $errorInfo[0] . ")", 0); } return $stmt->fetchAll($fetchStyle); } catch (PDOException $e) { $this->errorInfo = $e->getMessage(); return false; } }
/** * Executes SQL statement, possibly with parameters, returning * an array of all rows in result set or false on (non-fatal) error. */ function query() { $servername = "localhost"; $username = "******"; $password = "******"; $myDB = "bart"; try { //connect to server and the chosen database $conn = new PDO("mysql:host={$servername};dbname={$myDB}", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //echo "Connected successfully"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } // SQL statement $sql = func_get_arg(0); // parameters, if any $parameters = array_slice(func_get_args(), 1); // prepare SQL statement $statement = $conn->prepare($sql); if ($statement === false) { // trigger (big, orange) error trigger_error($conn->errorInfo()[2], E_USER_ERROR); exit; } // execute SQL statement $results = $statement->execute($parameters); // return result set's rows, if any if ($results !== false) { return $statement->fetchAll(PDO::FETCH_ASSOC); } else { return false; } }
public function insert($table, $columns) { $columnString = implode(', ', array_keys($columns)); $placeholderValues = []; foreach ($columns as $columnName => $value) { $placeholderValues[':' . $columnName] = $value; } $placeholderString = implode(', ', array_keys($placeholderValues)); $sql = 'INSERT INTO ' . $table . '(' . $columnString . ') VALUES (' . $placeholderString . ')'; echo '>>> Executing "' . $sql . '" with params: ' . $this->getParamsForEcho($placeholderValues) . PHP_EOL; $stmt = $this->pdo->prepare($sql); if (!$stmt instanceof \PDOStatement) { throw new \InvalidArgumentException(print_r($this->pdo->errorInfo())); } return $stmt->execute($placeholderValues); }
public function loadDatabaseData(stdClass $params) { try { ini_set('memory_limit', '-1'); if ($this->databaseConn($params->dbHost, $params->dbPort, $params->dbName, $params->dbUser, $params->dbPass)) { if (file_exists($sqlFile = 'sql/gaiadb_install_data.sql')) { $query = file_get_contents($sqlFile); if ($this->conn->exec($query) !== false) { return ['success' => true]; } else { FileManager::rmdir_recursive("sites/{$params->siteId}"); if (isset($params->rootUser)) { $this->dropDatabase($params->dbName); } throw new Exception($this->conn->errorInfo()); } } else { FileManager::rmdir_recursive("sites/{$params->siteId}"); if (isset($params->rootUser)) { $this->dropDatabase($params->dbName); } throw new Exception('Unable find installation data file'); } } else { FileManager::rmdir_recursive("sites/{$params->siteId}"); throw new Exception($this->err); } } catch (Exception $Error) { return ['success' => false, 'error' => $Error->getMessage()]; } }