I am new to PDO PHP. I have created a post data function in order to achieve the insertion functionality. Here is my code.
public function PostData($conn, $table, $data)
{
try {
$query = "INSERT INTO " . $table . "(";
$arraylen = count($data);
$keyloopcount = 0;
foreach ($data as $key => $values) {
$query .= $key;
if ($keyloopcount != $arraylen - 1) {
$query .= ",";
}
$keyloopcount++;
}
$valloopcount = 0;
$query .= ") VALUES (";
foreach ($data as $key => $values) {
$query .= "':" . $key . "'";
if ($valloopcount != $arraylen - 1) {
$query .= ",";
}
$valloopcount++;
}
$query .= ")";
$stmt = $conn->prepare($query);
foreach ($data as $key => &$values) {
$stmt->bindParam(':'.$key, $values, PDO::PARAM_STR);
}
if ($stmt->execute()) {
$stmt->debugDumpParams();
echo "me";
} else {
echo "die";
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
When I execute this query. It doesn't show any exceptions. but when I look into my Database. It shows inserted records as follows.
I am wondering if there is a way I can debug what are the values in the binded params. I have also looked for $stmt->debugDumpParams(); as shown in the code. But it doesn't shows the values of params.
Need Guidance. TIA.
I sorted it out. I was making a silly mistake. The solution was so simple and easy.
Solution
The problem was lying in the part of the code.
foreach ($data as $key => $values) {
$query .= "':" . $key . "'";
if ($valloopcount != $arraylen - 1) {
$query .= ",";
}
$valloopcount++;
}
Changed the code to:
foreach ($data as $key => $values) {
$query .= ":" . $key;
if ($valloopcount != $arraylen - 1) {
$query .= ",";
}
$valloopcount++;
}
Resultant Query Before Amendment:
INSERT INTO cmp_categories(cat_name,cat_slug,cat_desc) VALUES (':cat_name',':cat_slug',':cat_desc')
Resultant Query AfterAmendment:
INSERT INTO cmp_categories(cat_name,cat_slug,cat_desc) VALUES (:cat_name,:cat_slug,:cat_desc)
More Clearly,
Removed ' from VALUES clause. ':cat_desc' => :cat_desc
Related
i want to write this query in laravel can anyone please help me please. i am new to laravel.
public function selectTableData($table,$condition)
{
try{
$query = "SELECT * from ".$table;
if(is_array($condition))
{
$query .= " WHERE ";
foreach ($condition as $key => $value)
$query .= $key . "= '".$value."' AND ";
$query = rtrim($query,'AND ');
}
$result = mysql_query($query);
if (!$result)
throw new Exception(mysql_error());
if (mysql_num_rows($result) > 0) {
return mysql_fetch_assoc($result);
}
else
return false;
} catch ( Exception $e ) {
throw new Exception($e->getMessage ());
}
}
And this aswell, i want to write this code in laravel query format
public function insertTableData($table,$data)
{
try{
// generate insert query
if(is_array($data)){
$query = 'INSERT INTO '. $table.' ( ';
foreach ($data as $key => $value)
$query .= $key . ',';
$query = rtrim($query,',');
$query .= ') VALUES (';
foreach ($data as $key => $value)
$query .= '"'.$value.'",';
$query = rtrim($query,',');
$query .= ')';
$result = mysql_query($query);
//if (!$result) {
// throw new Exception( 'Could not run query: ' . mysql_error());
//}
return $result;
}
else
return false;
} catch ( Exception $e ) {
throw new Exception($e->getMessage ());
}
}
if it is in capsule format then it wil be good
You can write this query in laravel like below.
$query = DB::table($table);
if(is_array($condition)) {
foreach ($condition as $key => $value) {
$query->where($key, "'" . $value . "'");
}
}
$result = $query->get();
if (count($result) > 0) {
return $result;
} else {
return false;
}
Let me assume that your eloquent model class is SomeModel. Then You could try like the following for first query/method-
$query = new SomeModel();
if(is_array($condition))
{
foreach ($condition as $key => $value)
$query = $query->where($key, $value);
}
$result = $query->get();
And for the second-
if(is_array($data)){
$query = new SomeModel();
foreach ($data as $key => $value)
$query->$key = $value;
$query->save();
}
Hope it solves your problem :)
I have the following code but i am not sure how to check if insert is success. execute returns resource id. I would like to check if success and return all errors on fail.
public function persist()
{
$update = FALSE;
if(!is_array($this->tablePrimaryKey)) {
if(!empty($this->fieldVals[$this->tablePrimaryKey])) {
$update = true;
}
}
if ($update) {
$sql = "UPDATE " . $this->tableName . " SET ";
$binds = [];
foreach ($this->fieldVals as $key=>$val) {
if ($key != $this->tablePrimaryKey) {
if(in_array($key, $this->DATE_IDS)) {
$sql .= '"' . strtoupper($key) . '" = sysdate,';
} else {
$bind = 't_' . $key;
$binds[$bind] = $val;
$sql .= '"' . strtoupper($key) . '" = :' . $bind . ',';
}
}
}
$sql = substr($sql,0,-1);
$sql .= " WHERE " . $this->tablePrimaryKey . " = '" . $this->fieldVals[$this->tablePrimaryKey] ."'";
} else {
$binds = $fields = $date_fields = [];
if(!empty($this->tablePrimaryKey) && !is_array($this->tablePrimaryKey)) {
$this->fieldVals[$this->tablePrimaryKey] = $this->generateNewPrimaryKey();
}
foreach ($this->fieldVals as $key=>$val) {
$bind = ':t_' . $key;
if (in_array($key, $this->DATE_IDS)) {
$date_fields[] = strtoupper($key);
} else {
$binds[$bind] = $val;
$fields[] = strtoupper($key);
}
}
$sql = 'INSERT INTO ' . $this->tableName . '("' . implode('","', $fields);
if(count($date_fields) >0) {
$sql .= '","';
$sql .= implode('","', $date_fields);
}
$sql.='") VALUES (' . implode(',', array_keys($binds));
if(count($date_fields) >0) {
$cnt=0;
foreach($date_fields as $date) {
$cnt++;
if(preg_match('/NULL/i', $this->fieldVals[strtolower($date)], $result)) {
$sql .= ",NULL";
} elseif(isset($this->fieldVals[strtolower($date)])) {
$sql .= ",TO_DATE('" . (new DateTime($this->fieldVals[strtolower($date)]))->format("Y-M-d H:i:s") . "', 'yyyy/mm/dd hh24:mi:ss')";
} else {
$sql .= ",sysdate";
}
}
}
$sql .= ')';
}
$this->oiDb->parse($sql, $binds);
return $this->oiDb->execute();
}
I run $result = $oiRequests->hydrate($reportingRequest)->persist();. $reportingRequest is key,value pair of columns/values. $result contains resource id. $oiRequests is my model.
I have tried
$num_rows = oci_fetch_assoc ($result);
print_r($num_rows);
returns
Warning: oci_fetch_assoc(): ORA-24374: define not done before fetch or execute and fetch in /var/SP/oiadm/docroot/dev/uddins/requestportal/requestportal_ajax.php on line 65
Most of the OCI functions return false on error. This means you can do a simple check on the return value and, if it's false, call oci_error().
For the specific case of checking if an INSERT statement worked you can reference the example code for oci_commit(). The relevant part of that example is duplicated here:
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
When I try to update a table with the following query string using PHP:
UPDATE card_designs SET `card_price` = '6180',
`annual` = '257.3',
`initial_payment` = '6512.3'
WHERE card_id = '1'
It does not update correctly. card_price value is put in correctly. However annual comes in as 0 and initial_payment comes in as 6255.00.
It doesn't matter if the fields are a VARCHAR, DECIMAL, or DOUBLE. If the value has a decimal it's all messed up.
Also, if I run the above query in a SQL client, the query works fine.
Here is the PHP code that constructs the query. I'm using mysqli:
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value) {
array_push($updates, "`$field` = '$value'");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where)) {
foreach ($where as $field => $value) {
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit)) {
$sql .= ' LIMIT '. $limit;
}
$query = $this->mysqli->query($sql);
I assume your database table fields datatype is Decimal(9,2)
// Prepare query
$table = "card_designs";
$variables = array(
"card_price" => "6180.00",
"annual" => "257.3",
"initial_payment" => "6512.3"
);
$where = array(
"id" => "1"
);
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value)
{
array_push($updates, "$field = $value");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where))
{
foreach ($where as $field => $value)
{
$value = $value;
$clause[] = "$field = $value";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit))
{
$sql .= ' LIMIT '. $limit;
}
// Run query
if ($mysqli->query($sql))
{
echo "Record updated successfully";
}
I am currently going through a nettuts.com tutorial on building a twitter clone and there they have a function for deleting rows from a database and they are using the query method but i tried converting the function to a prepared statement.However I get the Invalid parameter number: parameter was not defined error.Here is the code for the function
public function delete($table, $arr){
$query = "DELETE FROM " . $table;
$pref = "WHERE ";
foreach ($arr as $key => $value) {
$query .= $pref. $key . " = " . ":" . $key;
$pref = "AND ";
}
$query .= ";";
$result = $this->db->prepare($query);
$result->execute($arr);
}
$connect = new Model();
$connect->delete("ribbits", array("user_id" => 2,
"ribbit" => "trial ribbit"
));
can someone please tell me what I am doing wrong?Thank you!
When you pass your array to ->execute(), the keys need to have the : character before them (just like they appear in the SQL query).
So, in your delete function, build the SQL query like this:
public function delete($table, $arr){
$keys = array();
$values = array();
foreach($arr as $key => $value){
$keys[] = $key . " = :" . $key;
$values[":".$key] = $value;
}
$query = "DELETE FROM " . $table . " WHERE " . implode(" AND ", $keys);
$result = $this->db->prepare($query);
$result->execute($values);
}
I have this function
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$arr = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
$set = "";
foreach($arr as $key => $v) {
$val = is_numeric($v) ? $v : "'" . $v . "'";
$set .= $key . '=' . $val . ', ';
}
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id']);
} else { echo "Done!"; }
echo $sql;
}
It outputs for example: UPDATE projects SET project_name='123', project_bold='123', project_content='123', WHERE id='12'
The last comma before where is preventing it from working. Is there a way of avoiding this? Im aware of the function implode, however I am not sure how to employ it in this situation.
Yes,
$sql = substr($sql,'',-1);
I would use
$sql = rtrim($sql, ',');
Either that or instead of appending to a string, append to an array and use implode.
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);