$sqlArray = array();
$nameArray = array();
$valueArray = array();
foreach ($_POST as $name => $value) {
$nameArray[] = $name;
$valueArray[] = $value;
}
$names = implode(', ', $nameArray);
$values = implode(', ', ':'.$nameArray);
$sql = "INSERT INTO customers ( ".$names." ) VALUES ( ".$values." )";
print_r($sql);
$addRandom = $pdo->prepare( $sql );
foreach($_POST as $name => $value) {
$addRandom->bindValue($name, $value);
}
$boolean=$addRandom->execute();
if($boolean){
echo 'INSERTED';
}else{
echo 'FAILED';
}
i am facing some problem while running this code.. please help me to fix this. showing error in implode(', ', ':'.$nameArray)
$fields = array_keys($_POST);
if (!empty($fields)) {
$names = implode('`, `', $fields);
$values = implode(', :', $fields);
$sql = "INSERT INTO customers ( `".$names."` ) VALUES ( :".$values." )";
print_r($sql);
$addRandom = $pdo->prepare($sql);
foreach ($fields as $field) {
$addRandom->bindValue(":{$field}", $_POST[$field]);
}
$boolean = $addRandom->execute();
if ($boolean){
echo 'INSERTED';
} else {
echo 'FAILED';
}
}
Related
I need some help please.
Currently my mariadb is set up with one column as a json array.
I would like to search the array from a users input, then combine it with the first and last name of the user stored in the database.
In the database:
Columns: firstname, lastname and suburbs_i_cover (containing the json array)
ex: ["Pretoria","Cape Town","Garden Route"]
I would like the sql statement that would search the suburbs_i_cover and allow me to combine the first and last name.
So far I have this:
<?php
//echo JUri::getInstance();
if (isset($_GET['category'])) {
$catetogry = $_GET['category'];
$name = $_GET['name'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = ("SELECT * FROM #__jsn_users"); //not sure what goes here
$db->setQuery($query);
$results = $db->loadObjectList();
foreach($results as $obj) {
$value = json_decode($obj->suburbs_i_cover);
$value = array_filter($value, 'strlen'); //removes null values
but leaves "0"
$value = array_filter($value); //removes all null
values
if (!empty($value)) {
$value2 = $obj->firstname;
$value3 = $obj->lastname;
echo $value2 . ' '. $value3;
//echo "<br>";
// echo sizeof($value);
echo "<br>";
if (is_array($value)) {
foreach ($value as $sub_value) {
echo $sub_value;
echo "<br>";
}
}
echo "<br>";
echo "<hr>";
}
}
}
I got a working solution:
To use: in_array($name, $value)
<?php
//echo JUri::getInstance();
if (isset($_GET['category'])) {
$catetogry = $_GET['category'];
$name = $_GET['name'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = ("SELECT * FROM #__jsn_users");
$db->setQuery($query);
$results = $db->loadObjectList();
foreach($results as $obj) {
$value = json_decode($obj->suburbs_i_cover);
$value = array_filter($value, 'strlen'); //removes null values
but leaves "0"
$value = array_filter($value); //removes all null
values
if (in_array($name, $value)) {
$value2 = $obj->firstname;
$value3 = $obj->lastname;
echo $value2 . ' '. $value3;
echo "<br>";
echo "<hr>";
}
}
}
?>
I have been retrieving call logs from a cdr and dumping them into a database in MySQL. Of late the database crashes and the was giving me duplicates and junk characters so i modified to the below code.
modified code
$file1 = file_get_contents('file:///C:/Users/thy/Desktop/2011_0419_1531_v3.12R/cdr/'.$newname, FILE_USE_INCLUDE_PATH);
$arr1 = explode("\n", $file1);
foreach ($arr1 as $key => $value) {
$colArray = [];
$colArray['id'] = null;
$colArray['hashkey'] = md5(uniqid(rand(), true));
$split = explode(";", $value);
foreach ($split as $key => $val) {
# code...
$arr = (explode('=', $val));
$field = 'ch';
$item = '0';
$field = $arr[0];
$item = $arr[1];
$item = str_replace(str_split(')(\/'), '', $item);
$colArray[$field] = $item;
}
$columns = implode(', ', array_keys($colArray));
$values = implode(', ', $colArray);
$sql = "INSERT INTO `call`.`logs` (" . $columns . ") VALUES (" . $values . ")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
the above code keeps giving me errors
Error: INSERT INTO call.logs (id, hashkey, ) VALUES (,
797d8782a433b30e196fafc0ce01d09b, )You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near ') VALUES (,
797d8782a433b30e196fafc0ce01d09b, )' at line 1
Original code is below (the one i modified it from)
$file1 = file_get_contents('file:///C:/Users/thy/Desktop/2011_0419_1531_v3.12R/cdr/'.$newname, FILE_USE_INCLUDE_PATH);
$arr1 = explode("\n", $file1);
$data1 = array();
foreach ($arr1 as $key => $value) {
$split = explode(";", $value);
$keys = md5(uniqid(rand(), true));
//insert key to identify call.
$sql = "INSERT INTO `call`.`logs` (`id`, `hashkey`) VALUES (NULL, '{$keys}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
foreach ($split as $key => $val) {
# code...
$arr=(explode('=', $val));
$field='ch';
$item='0';
$field=$arr[0];
$item=$arr[1];
echo $field . " --";
echo "<br/>";
echo $item;
//sql
$sql = "UPDATE logs SET {$field}='{$item}' WHERE hashkey='{$keys}'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
echo "done";
//$conn->close();
} echo "<br/>";
}
?>
<?php
I think the problem is with the generated/devised INSERt statement
INSERT INTO call.logs (" . $columns . ") VALUES (" . $values . ")";
There is an extra comma getting appended without column name?
If id is an autoincremental field. Try this:
INSERT INTO call.logs (id, hashkey) VALUES (default, '797d8782a433b30e196fafc0ce01d09b')
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 have a update function that for now updates the required changes to MySQL database when I run index.php.
This is updating my password buy not the name field, ive been over the code and can not work out why.
Any help is greatly appreciated.
Index that tells what id and fields to update with entered data
<?php
require_once 'core/init.php';
$userInsert = DB::getInstance()->update('users', 1, array(
'password' => 'newpass',
'name' => 'Ben'
));
Function in different php that updated database
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} = 'newpassword' WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
I believe it to be a small error or mistype but I can not see the problem.
As you can see bellow the password field has been changed but the name has not
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = \"{$value}\"";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
Simply use of prepare and execute in PDO:
$sql = 'UPDATE '. $table .' SET username = :username, password = :password WHERE id = '. $id;
$sth = $dbh->prepare($sql);
$sth->execute(array(
':username' => 'ben',
':password' => 'newpassword'
));
private function update($table, $primaryKey, $fields) {
$query = 'UPDATE `' . $this->table . '` SET ';
foreach ($fields as $key => $value) {
$query .= '`' . $key . '` = :' . $key . ',';
}
$query = rtrim($query, ',');
$query .= ' WHERE `' . $this->primaryKey . '` = :primaryKey';
$fields['primaryKey'] = $fields['id'];
$this->query($query, $fields);
}
An example of an update function. Attention mine is inside a class and the query is another function and passes as an object.
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);