So, i have researched this everywhere and i can't see why its inserting blanks. I use pretty much the same code in another file and that one works fine. Any Help?
<?php
//Connection
$first_name = mysqli_real_escape_string($_POST [' first_name ']) ;
$last_name = mysqli_real_escape_string($_POST [' last_name ']) ;
$email = mysqli_real_escape_string($_POST [' email ']) ;
$message = mysqli_real_escape_string($_POST [' message ']) ;
$insert_sql = "INSERT INTO generaldis (first_name, last_name, email, message)
VALUES ('$first_name', '$last_name' , '$email' , '$message');";
if (!mysql_query($insert_sql,$link))
{
die('Error: ' . mysql_error());
}
echo '<h1>Whoop! Your Message Has Been Posted!</h1><br><p>Click Here To Go Back</p>';
?>
try this:
$fields = array(
'first_name' => "/[a-zA-Z-_]+/",
'last_name' => "/[a-zA-Z-_]+/",
'email' => '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/',
'message' => null
);
$permit = true;
foreach($fields AS $field => $regexp) {
if(is_null($regexp)) continue;
if(!preg_match($regexp, $_REQUEST[$field])) {
$permit = false;
break;
}
}
if($permit) {
$query = "INSERT INTO general_dis SET ";
$values = array();
foreach($fields AS $field => $regexp) {
$value = $_REQUEST[$field];
if(is_null($regexp)) {
$value = mysql_real_escape_string($value);
}
$values[] = "`".$field."`='".$value."' ";
}
$values = implode(', ', $values);
$query .= $values;
mysql_query($query);
}
Related
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";
}
$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';
}
}
I have the following code in an application I'm building and to be honest... it feels like a great deal of pain when I want to change something like this. I've always had this problem with SQL in code but never understood how to address it. Is there some way or common practice that would make the SQL here a bit easier to maintain and change? (I've read not to use stored procedures)
$stmt_arr = array(
':steamid' => isset($playerSummary['steamid']) ? $playerSummary['steamid'] : "",
':personaname' => isset($playerSummary['personaname']) ? utf8_encode($playerSummary['personaname']) : "",
':community_vis_state' => isset($playerSummary['communityvisibilitystate']) ? $playerSummary['communityvisibilitystate'] : "",
':profile_state' => isset($playerSummary['profilestate']) ? $playerSummary['profilestate'] : "NULL",
':profile_url' => isset($playerSummary['profileurl']) ? $playerSummary['profileurl'] : "",
':avatar_url' => isset($playerSummary['avatar']) ? $playerSummary['avatar'] : "",
':avatar_medium' => isset($playerSummary['avatarmedium']) ? $playerSummary['avatarmedium'] : "",
':avatar_full' => isset($playerSummary['avatarfull']) ? $playerSummary['avatarfull'] : "",
':shallow_update' => $isFriend
);
$stmt = $this->DBH->prepare("INSERT INTO `user`(`steamid`, `personaname`, `community_visibility_state`, "
. "`profile_state`, `profile_url`, `avatar_url`, `avatar_medium_url`, `avatar_full_url`, `last_updated`, `shallow_update`)"
. " VALUES (:steamid, :personaname, :community_vis_state, :profile_state, :profile_url, "
. ":avatar_url, :avatar_medium, :avatar_full, NOW(), :shallow_update) "
. "ON DUPLICATE KEY UPDATE `steamid` = VALUES(`steamid`), "
. "`personaname` = VALUES(`personaname`), "
. "`community_visibility_state` = VALUES(`community_visibility_state`), "
. "`profile_state` = VALUES(`profile_state`), "
. "`profile_url` = VALUES(`profile_url`), "
. "`avatar_url` = VALUES(`avatar_url`), "
. "`avatar_medium_url` = VALUES(`avatar_medium_url`), "
. "`avatar_full_url` = VALUES(`avatar_full_url`), "
. "`last_updated` = VALUES(`last_updated`),"
. "`shallow_update` = VALUES(`shallow_update`)");
$stmt->execute($stmt_arr);
Use this function
function pdo_insert($con, $table, $data_arr)
{
if (!is_array($data_arr) || !count($data_arr)) return false;
$bind = ':'.implode(',:', array_keys($data_arr));
$sql = 'INSERT into '.$table.'('.implode(',', array_keys($data_arr)).') '.
'values ('.$bind.')';
$stmt = $con->prepare($sql);
$status = $stmt->execute(array_combine(explode(',',$bind), array_values($data_arr)));
if($status)
{
// success
$msg = 'Data added to database successfully';
return $msg;
}
else
{
// failure
$msg = 'Error in adding data into database';
return $msg;
}
}
Calling the function
$msg = pdo_insert($db, 'table name here', $_POST);
// see the result
echo $msg;
function generateSQL($table, $arr) {
$sql = "INSERT INTO ".$table . " (";
foreach($arr as $k => $v) {
$sql .= "`".substr_replace($k, "", 0, 1)."`, ";
}
$sql = substr_replace($sql, "", -2);
$sql .= ") VALUES (";
foreach($arr as $k => $v) {
$sql .= $k.", ";
}
$sql = substr_replace($sql, "", -2);
$sql .= ") ON DUPLICATE KEY UPDATE ";
foreach($arr as $k => $v) {
$sql .= "`".substr_replace($k, "", 0, 1)."` = VALUES(`".substr_replace($k, "", 0, 1)."`), ";
}
$sql = substr_replace($sql, "", -2);
return $sql;
}
print_r(generateSQL("user", $stmt_arr));
Where did you read not to use stored procedure ?
They are the solution to your problem, when queries get complex, it is better to move the logic to a sotored procedure and just execute it (e.g CALL sp_isnert_user ?, ?)
They also allow you to maintain/modify your SQL logic without really touching your code.
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);