how to insert multiple variables into a sql query - php

<?php
session_start();
include('function.php');
site::db();
$type=$_GET['type'];
$date=$_GET['date'];
$amount=$_GET['amount'];
switch($type) {
case "in_park":
$table = "lot_income";
$col = "date,amount";
$val = $date $type $amount;
break;
}
$sql = mysql_query("INSERT INTO $table ($col) VALUES ('$val')");
if(!$sql) {
die(mysql_error());
}
//header("LOCATION: dashboard.php")
?>
This will not work but im assuming that i will will need to explode the variables val but how to i put the comma in there too so i can put the info in many different field other than just one field.

Change this..
$val=$date $type $amount;
Into this
$val= "'$date', '$amount'";
And thius
$sql=mysql_query("INSERT INTO $table ($col) VALUES ('$val')");
into this
$sql=mysql_query("INSERT INTO $table ($col) VALUES ($val)");

I think you are missing a column in your SQL statement:
$col = "date, type, amount";
You will need to format the SQL values accordingly:
$val = "'$date', '$type', '$amount'";
Concatenate them:
$sql = mysql_query("INSERT INTO $table ($col) VALUES ($val)");

I usually do:
$table = "lot_income";
$data = array(
'date' => "'".mysql_real_escape_string($date)."'", // date
'type' => intval($type), // integer
'amount' => intval($amount), // integer
'text' => "'".mysql_real_escape_string($sometext)."'" // string
// etc
);
// I tend to wrap the following statement in a function for code reuse
$resource = mysql_query(
"INSERT INTO ".$table." (".implode(", ", array_keys($data).")"
. "VALUES (".implode(", ", array_values($data).")"
);
Note: for values escaping (in order to avoid SQL injections), it would be easier/safer to bind variables by using PHP extension PDO or mysqli.

Related

why can't I save the current date in my database on mysql?

why can't I save the current date in my database on mysql, all columns here enter except the date which only displays 0000-00-00 in the database
<?php
require_once 'koneksi.php';
if (isset($_POST['submit'])) {
foreach ($_POST['keterangan'] as $id => $keterangan) {
$nama_siswa = $_POST['nama_siswa'][$id];
$kelas = $_POST['kelas'][$id];
$peminatan = $_POST['peminatan'][$id];
$waktu = date("Y-m-d H:i:s");
$sql = "INSERT INTO kehadiran VALUES ('','$nama_siswa', '$kelas', '$peminatan', '$keterangan', $waktu )";
$result = mysqli_query($conn, $sql);
if ($result) {
header("location:index.php?page=home.php");
} else {
echo "failed data added";
}
}
}
?>
From an initial look, it seems you forgot to enclose your variable $waktu with single quote, as in Mysql datetime values should be enclosed by quotes similar to string values. so the query should be updated as following:
$sql = "INSERT INTO kehadiran VALUES ('','$nama_siswa', '$kelas', '$peminatan', '$keterangan', '$waktu' )"
You should put CURDATE() function in the code replacing
$waktu

PHP check numeric value inside foreach loop with keys and values pairs?

I am trying to check associative array value if it is numeric, here is my code
$data = array('fullname'=>'Salah Saed', 'age'=>'33', 'gender'=>'Female');
public function insert($data, $table){
/*$query = "INSERT INTO `oop_crud`.`customers` (";
$query .= "`fullname` , `age` , `gender` )";
$query .= "VALUES ('".$fullname."', '".$age."', '".$gender."')";
*/
$feilds = array();
$feilds_value = array();
foreach ($data as $field => $field_value){
$feilds[] = $field;
echo $field;
if (is_numeric($field_value)){
$feilds_value[] = $field_value;
}else{
$feilds_value[] = "'".$field_value."'";
}
}
$query = "INSERT INTO ".$table." (";
$query .= implode(',', $feilds).")";
$query .= "VALUES (";
$query .= implode(',',$feilds_value).")";
echo $query;
It returns string, so what is wrong with my code,
in the condition section i used $field_value and this variable has array data, sow how to get array value.
First of all, MySQL inserts are type-independent, so
SET UserAge = '33'
is the same as
SET UserAge = 33
so you would be safer to just add quotes. That said, you're safest if you search for prepared statements using PDO (aka parametrized queries). Take a look at that
http://php.net/is_numeric is supposed to recognize values like 0x539 and 0b10100111001 which may not be recognized by MySQL; you would need to check these cases.
Here is simplified version of your function, in case you want to improve your query generator function,
function insert($data, $table){
$column_sql = '`' . implode('`,`', array_keys($data)) . '`';
$record_sql = "'" . implode("','", $data) . "'";
return "INSERT INTO `{$table}` ({$column_sql}) VALUES ({$record_sql})";
}
Feeding it $data and test will give
INSERT INTO `test` (`fullname`,`age`,`gender`) VALUES ('Salah Saed','33','Female')
NOTE: Need to escape values mysqli_real_escape_string(), i'll leave that upto you, as an exercise :)

Adding quotes to array values in php

The following script is used to implode values from a multidimensional array and insert into the mysql table. The table contains field data types of varchar and decimal. Since varchar type requires quotes and to avoid selectively placing quotes, I would like to put all values in quotes. How to implement it?
$values = array();
foreach ($data as $rowValues) {
foreach ($rowValues as $key => $rowValue) {
}
$values[] = "(" . implode(', ', $rowValues) . ",'".$date."')";
}
$query = "INSERT INTO mem (memno,loan,subsc,intst, date)
VALUES " . implode (', ', $values);
$result=mysql_query($query) or die();
I want the sql like this
INSERT INTO mem (memno,loan,subsc,intst, date)
values('value1', 'value2', 'valu3','value4','value5')
Don't use user input to build SQL strings - thats how you get SQL injection attacks.
Instead use a prepared statement:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("
INSERT INTO mem( memno, loan, subsc, intst, date )
VALUES (?, ?, ?, ?, ?);
");
$stmt->bind_param('sssss', $memno, $loan, $subsc, intst, $date);
edit in response to the comment:
Dynamically binding an array of columns is pretty easy with PDO.
$db =new PDO("mysql:host=localhost;dbname=database;","root","");
/**
* #param PDO $db
* #param string $table - the table to insert into
* #param array $columns - which columns do we want to insert into
* #param array $data - a key/value array of the data we want to insert
* #return bool
*/
function insert_into($db, $table, array $columns, array $data) {
$rows = implode(', ', $fields);
$placeholders = array_map ( function($key){ return ":$key" }, $fields);
$placeholders = implode(', ', $fields);
$sql = "
INSERT INTO $table ($fields)
VALUES ($placeholders);
";
$stmt = $db->prepare($sql);
foreach( $fields as $field) {
$stmt->bindParam(":$field", $data[$field]);
}
return $sth->execute();
}
$inserted = insertInto(
$db
'mem',
array("memno", "loan", "subsc", "intst", "date"),
$data
);
Notice that the columns to insert are defined separately.
If I had used:
array_keys($data);
It would lead to a mass assigment vulnerability if $data comes from user input and is not whitelisted.
You can accomplish the same thing with mysqli but its a bit trickier.
If $rowValues array is as below then you can do like this also.
$rowValues = array(
"memno"=>"a",
"loan"=>"b",
"subsc"=>"c",
"intst"=>"d"
);
$fldStr = array();
$valStr = array();
foreach($rowValues as $key=>$val) {
array_push($fldStr, $key);
$v2 = "'" . $val . "'";
array_push($valStr, $v2);
}
array_push($fldStr, "date");
array_push($valStr, "'" . $date . "'");
$flds = implode(", ", $fldStr);
$vals = implode(", ", $valStr);
$query = "INSERT INTO mem ($flds) values($vals)";

Add data into php mysql with single quotes

This is my code:
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = $e['BRAND'];
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}
Since in "BRAND", there may be some data like "First's Choice".
In this case, I cannot insert to database due to error.
How can I insert data that contain single quotes?
Thx
you need to use mysql_real_escape_string on the value, which you should be doing anyway. That should properly escape your value for insertion.
$name = mysql_real_escape_string($e['NAME']);
$brand = mysql_real_escape_string($e['BRAND']);
$category = mysql_real_escape_string($e['CATEGORY']);
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
Use mysql_real_escape_string
You must use :
$brand = mysql_real_escape_string($brand)
See PHP Documentation.
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
Escapes special characters in
the unescaped_string, taking into account the current character set of
the connection so that it is safe to place it in a mysql_query(). If
binary data is to be inserted, this function must be used. (..)
Try below code
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = mysql_real_escape_string($e['BRAND']);
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}
There are two ways of accomplishing that. You can first run an escape string on it:
$newbrand = mysql_real_escape_string($brand);
and insert $newbrand. When you call it, you have to do strpslashes($newbrand);
OR you could do:
$search = array("'");
$newbrand = str_replace($search,'',$brand);
I was pulling my hair to solve this, finally i am ok with this solution. Try this

how to insert array of data into database

here my code-
$things = mysql_real_escape_string(implode(',', $_POST['things']),$link);
$q = "INSERT INTO tblslider(src) VALUES ('".$things."')";
print_r($q);
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
but my query is getting generated
INSERT INTO tblslider(src) VALUES ('4368122.jpg,5440051.jpg,1047428.jpg') but it should be
INSERT INTO tblslider(src) VALUES ('4368122.jpg'),('5440051.jpg'),('1047428.jpg') thats why it is taking it as one record not three.
You could do:
$things = array_map('mysql_real_escape_string', $_POST['things']);
$q = "INSERT INTO tblslider(src) VALUES ('". implode("'),('", $things)."')";
It generates (with my test data):
INSERT INTO tblslider(src) VALUES ('a.jpg'),('b.jpg'),('c.jpg')
I forgot: Only use functions like mysql_real_escape_string on the real data, not the SQL string. In your example you apply the function on the already concatenated data.
You have imploded things which is now an array, so you need to iterate over this with a foreach loop such as...
foreach ($things as $item) {
$q = "INSERT INTO tblslider(src) VALUES ('".$item."')";
echo '<br />'.$q;
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
}
You could echo $q to make sure you're getting the queries right for each item also.
try this:
$formatVals = function($x){$rx = mysql_real_escape_string($x); return "('$rx')";};
$valString = implode(',', array_map($formatVals, $_POST['things']);
$sql = "INSERT INTO tblslider (src) VALUES $valString";

Categories