i'm trying to insert multiple data using a query, i've tried the implode function, the while loop, for loop, but still can't be done..
can u help plz
well i've a combobox box for selecting course name, created a function to get its ID and assign a variable. supose i'm a manager of a department and need to assign all staff below me a course, i select the course, input the date assigned and expected ending date. i've created another field in database to enter the training owner. Since i'm the 1 assigning the course, my name will appear as owner field.
$m_name = $_SESSION['SESS_FIRST_NAME'];
//combobox to get the department ID using variable $dept
//query to get all user concerning the department
$query = mysql_query("select userid from dept_user where dept_id=$dept LIMIT 0, 30 ");
$row= mysql_query($query);
//from here i'm not being able to execute
$qry = mysql_query("INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('$query','$name','$sdate', '$edate', '$m_name')" ) ;
$qry = mysql_query("INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('$query','$name','$sdate', '$edate', '$m_name')" ) ;
So, you're basically trying to insert $query in the userid column. In your code, $query is the result of a mysql select statement, thus a multi-array of user ids. Think of it like a simple SQL query, you can't execute that. Even more, you're doing mysql_query on a mysql_query result, which is plain wrong. Where does the $dept variable come from? What about the others? If you're sure they're valid here's what you need:
// Get the user ids you need to insert in the db
$query = "select userid from dept_user where dept_id=$dept LIMIT 0, 30 "; // this will select the first 30 users in a dept
$buffer = mysql_query($query); // this is a variable that will hold all the results returned by the query above
// While we still have results in the $buffer array, fetch those in the $data array
while ($data = mysql_fetch_assoc($buffer)) {
$insert_query = "INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('".$data['userid']."','$name','$sdate', '$edate', '$m_name')"; // add the userid from the first query and the other data (don't know where you got those
$insert_buffer = mysql_query($insert_query); // execute the statement above, watch out so you don't overwrite the initial $buffer variable
}
// At this point you should have all the data in database
Also, I'm not sure you got the insert statement right
userid > $data['userid'] (ok)
course_id > $name (?!)
date_assign > $sdate (you sure?)
expected_end_date > $edate (ok)
owner > $m_name (ok?)
Make sure you have a good naming convention or else you get lost very easy.
Good luck, a lot of mistakes on just 5 lines of code.
Let's give it a wild guess and assume that this is what you want:
//query to get all user concerning the department
$query = mysql_query("
SELECT userid
FROM dept_user
WHERE dept_id=$dept
");
if(mysql_num_rows($query)){
$insertSQL = "
INSERT INTO course_detail
(userid, course_id, date_assign, expected_end_date, owner)
VALUES
";
$rowsSQL = Array();
while($row = mysql_fetch_row($query)){
$rowsSQL[] = "('{$row['userid']}','$name','$sdate', '$edate', '$m_name')";
}
mysql_query($insertSQL.implode(',', $rowsSQL));
}
Also you should start reading the manual.
Read the doc, you can separate each set of data with a comma.
$values = array();
$values[] = array(
'id' => 1,
'v1' => 'a',
'v2' => 'b'
);
$values[] = array(
'id' => 2,
'v1' => 'c',
'v2' => 'd'
);
$sql = "INSERT INTO course_details (id,v1,v2) VALUES ";
foreach ($values as $value) {
$sql .= '('.$value['id'].','.$value['v1'].','.$value['v2'].'),';
}
$sql = substr ($sql,0,-1) // that will remove the last comma
mysql_query($sql);
Below is the function and here is how to use it
Update Query
$data_array=array(
"bannername" => addslashes($_POST["bannername"]),
"url" => $_POST["url"],
"openin" => $_POST["openin"]
);
$param=" bannerid = '$bannerid'";
$sql=db_makequery("banner",$data_array,"update",$param);
Insert Query
$data_array=array(
"bannername" => addslashes($_POST["bannername"]),
"url" => $_POST["url"],
"openin" => $_POST["openin"]
);
$sql=db_makequery("banner",$data_array);
Function
function db_makequery($table, $data, $action = 'insert', $parameters = '')
{
reset($data);
if ($action == 'insert')
{
$query = 'insert into ' . $table . ' (';
while (list($columns, ) = each($data)) {
$query .= $columns . ', ';
}
$query = substr($query, 0, -2) . ') values (';
reset($data);
while (list(, $value) = each($data))
{
switch ((string)$value)
{
case 'now()':
$query .= 'now(), ';
break;
case 'null':
$query .= 'null, ';
break;
default:
//$query .= '\'' . tep_db_input($value) . '\', ';
$query .= '\'' . $value . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ')';
}
elseif ($action == 'update')
{
$query = 'update ' . $table . ' set ';
while (list($columns, $value) = each($data))
{
switch ((string)$value) {
case 'now()':
$query .= $columns . ' = now(), ';
break;
case 'null':
$query .= $columns .= ' = null, ';
break;
default:
//$query .= $columns . ' = \'' . tep_db_input($value) . '\', ';
$query .= $columns . ' = \'' . $value . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ' where ' . $parameters;
}
return $query;
}
Related
I've got below snippet where $filter_xx values are extracted from a dropdown basis user choice.
I'm trying to query the mySQL database with what the user chose to query the database with via dropdown selection.
You will see that there are 4 $filter_xx variables and how many of them are set in a given instance is completely random.
The issue is when I use && in the query it checks if all four parameters are true and then throws and output. (Well I know && is suppose to work that way!). I tried replacing all && operators with || and had no luck.
How do I search the database with only options selected by the user?
if(isset($filter_brand) || isset($filter_year) || isset($filter_month) || isset($filter_status))
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand' && startyear='$filter_year' && startmonth='$filter_month' && status='$filter_status' ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
When you have several values that must work in a similar manner, use an array together with loop. I am supposing, you are using mysqli, change quoting for PDO if needed.
$mysqli = new mysqli("localhost", "user", "pass", "test");
//...
//SQL attr name => name of POST parameter
$filter = array('brand' => 'brand', 'startyear' => 'year',
'startmonth' => 'month', 'status' => 'status');
//here we'll store SQL conditions
$sql_filter = array();
foreach($filter as $key => $value)
{
if (isset($_POST[$value]))
{
//use your library function to quote the variable before using it in SQL
$sql_filter[] = $key . '="'. $mysqli->escape_string($_POST[$value]) . '"';
}
}
$query = "SELECT * FROM targets ";
if(isset($sql_filter[0]))
{
$query .= 'WHERE ' . implode(' AND ', $sql_filter) . ' ';
}
$query .= 'ORDER BY createdon DESC';
Try By This
$join = "";
//TAKE ONE BLANK VARIBLE THAT JOIN IF VALUE IS SET
if(isset($filter_brand)){
//IF VALUE ISSET THAN IT ADDED TO QUERY
$join .= " AND brand='$filter_brand'";
}
if(isset($filter_year){
$join .= " AND startyear='$filter_year'";
}
$query = "SELECT * FROM targets WHERE id != '' $join ORDER BY createdon DESC";
You can do something like this:
$query = 'SELECT * FROM targets';
$flag = 0;
if(isset($filter_brand) )
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand'";
$flag = 1;
}
if(isset($filter_year)) {
if($flag==1)
$query .= " &&";
$query .= " startyear='$filter_year'";
$flag = 1;
}
if(isset($filter_month)) {
if($flag==1)
$query .= " &&";
$query = " startmonth='$filter_month'";
$flag = 1;
}
if(isset($filter_status)){
if($flag==1)
$query .= " &&";
$query = " status='$filter_status'";
$flag = 1;
}
if($flag == 1){
$query .= " ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
Try this:
$query = "SELECT * FROM targets WHERE 1 ";
$query = isset($filter_brand) ? $query . " AND brand = '".$filter_brand."'" : $query;
$query = isset($filter_year) ? $query . " AND startyear = '".$filter_year."'" : $query;
$query = isset($filter_month) ? $query . " AND startmonth = '".$filter_month."'" : $query;
$query = isset($filter_status) ? $query . " AND status = '".$filter_status."'" : $query;
$query .= " ORDER BY createdon DESC";
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";
}
Let's say i have and array like this
$array= Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
Keys from this array are name of columns in table and values are value of columns which i need to update.
I want to update the table based on keys and values.
I am using ADODB
Please help me
try this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
$sql .= $key . " = " . $value . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
and of course the WHERE clause:
$sql .= " WHERE condition = value";
you will get the string:
UPDATE table SET id = 3, name = NAME, age = 12 WHERE condition = value
L.E: You might need to add apostrophes to strings so I have to change my code to something like this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= " WHERE condition = value";
which will produce this:
UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE condition = value
L.E 2: If you want the id column in your condition, the code becomes this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if($key == 'id'){
$sql_condition = " WHERE " . $key . " = " . $value;
continue;
}
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= $sql_condition;
which will produce this result:
UPDATE table SET name = 'NAME', age = 12 WHERE id = 3
Hope this helps! :D
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
Source : https://stackoverflow.com/a/7884331/3793639
Other sources to check.
PHP SQL Update array and Simple UPDATE MySQl table from php array
You could use something like this for achieving that:
foreach($values as $value) {
if(!key_exists($value, $item)) {
return false;
}
$table->{$value} = $items[$value];
}
Assuming that the key index is always id and that adodb can use named placeholders you could do this:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$set = array();
$data = array();
while(list($key,$value)=each($array)) {
$data[':'.$key] = $value;
if($key!='id') {
$set[] = $key . ' = :' . $key;
// if no placeholders use $set[] = $key . " = '" . database_escape_function($value) . "'";
}
}
$sql = "UPDATE table SET ".implode($set, ',')." WHERE id=:id";
//$data is now Array(':id'=>'3', ':name'=>'NAME', ':age'=>'12');
//$sql is now "UPDATE table SET name=:name, age=:age WHERE id=:id";
$stmt = $DB->Prepare($sql);
$stmt = $DB->Execute($stmt, $data);
This is probably the shortest and easiest for you, you can also use something like this to achieve it:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$sql = "UPDATE table SET ";
$sql .= implode(', ', array_map(function($key, $value){
return is_numeric($value) ? "{$key} = {$value}" : "{$key} = '". mysql_real_escape_string($value). "'";
}, array_keys($array), $array));
$sql .= " WHERE id = 123";
// Result : UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE id = 123
I am creating search query in php by passing variable through GET method. When the variable is null then it's passing the query like,
SELECT * FROM table WHERE column_name = null.
And it's showing error (obvious). I want to create query like. If user don't select anything from search options then it should fetch all the data from that column.
What's the correct logic for that?
Thanks.
Code:
if(isset($_GET['selPetType']) && $_GET['selPetType'] != '')
{
$searchParams['petType'] = $_GET['selPetType'];
$queryStr .= " PetType='" .$_GET['selPetType']. "'";
}
if(isset($_GET['txtPetBreed1']) && !empty($_GET['txtPetBreed1']))
{
$searchParams['breed'] = $_GET['txtPetBreed1'];
$queryStr .= " AND PetBreed1 ='". $_GET['txtPetBreed1'] . "'";
}
$clause1 = "SELECT * FROM pet WHERE $queryStr ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit";
$totalRun1 = $allQuery->run($clause1);
Maybe something like this:
$get['param1'] = 'foo';
$get['param3'] = null;
$get['param2'] = '';
$get['param4'] = 'bar';
$where = null;
foreach ($get as $col => $val) {
if (!empty($val)) {
$where[] = $col . ' = "' . $val . '"';
}
}
$select = 'SELECT * FROM pet ';
if ($where) {
$select .= 'WHERE ' . implode(' AND ', $where);
}
$select .= ' ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit';
Edit: I added if to remove empty values and added 2 new values to example so you can see this values will not be in query.
if(isset($_GET['your_variable'])){
$whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}
$qry ="SELECT * FROM table WHERE ".$whr;
For example :
<?php
$userSelectedValue = ...;
$whereCondition = $userSelectedValue ? " AND column_name = " . $userSelectedValue : "" ;
$query = "SELECT * FROM table WHERE 1" . $whereCondition;
?>
Then consider it's more safe to use prepared statements.
I want to create sql queries dynamically depending upon the data I receive from the user.
Code:
$test = $_POST['clientData']; //It can be an array of values
count($test); //This can be 2 or 3 or any number depending upon the user input at the client
$query = "select * from testTable where testData = ".$test[0]." and testData = ".$test[1]." and . . .[This would vary depending upon the user input]"
Is it possible to achieve the above scenario. I am relatively new in this area.Your guidance would be helpful.
Use:
<?php
$test=$_POST['clientData'];//It can be an array of values
$query = "select *from testtable where 1 ";
foreach($test as $value) {
$query .= " AND testData='" . $value . "'";
}
echo $query;
?>
Use prepared statements:
$query = $dbh->prepare("SELECT * FROM testtable WHERE testData=:test0 and testData=:test1");
$query ->bindParam(':test0', $test0);
$query ->bindParam(':test1', $test0);
$test0 = $test[0];
$test1 = $test[1];
$query->execute();
Rishi that's a very long chapter.
If you want to search into a single field then you can try to do:
<?php
$test = $_POST[ 'clientData' ];
if( is_array( $test ) ){
$select = implode( ",", $test );
} else {
$select = $test;
}
$query=select *from testtable where testData IN ( $select );
?>
This is valid only for searches into a specific field.
If you want to create searches on multiple fields then you need to do a lot of more work, having an associative mapping which can create a relation variable name -> field_to_search
$data = $_POST['data'];
$query = "SELECT";
if ( is_set($data['columns']) )
$query .= " ".implode(',',$data['columns']);
else
$query .= "*";
if ( is_set($data['table']) )
$query .= " ".$data['table'];
and ...
This is very much pseudo code as I don't really know PHP, but could you not do something like this
$query = "select * from testable";
$count = count($test);
if($count > 0)
{
$query .= " where ";
for ($x=0; $x<=$count; $x++)
{
if($x > 0)
{
$query .= " and ";
}
$query .= " testData='" . $test[x] . "'";
}
}
$test=$_POST['clientData'];
$query="select * from testtable where testData='".$test[0]."' and testData='".$test[1]."' and . . .[This would vary depending upon the user input]";
$result = mysql_query($query);
$test=$_POST['clientData'];//It can be an array of values
$dValuesCount = count($test);//This can be 2 or 3 or any number depending upon the user input at the client
$query="select *from testtable ";
if ($dValuesCount > 0 ){
$query .= " WHERE ";
for ($dCounter = 0; $dCounter <= $dValuesCount ; $dCounter++){
$query .= "testData=" . $test[$dCounter];
if ($dCounter != ($dValuesCount - 1)){
$query .= " AND ";
}
}
}
$q="select *from table where ";
$a=count($test)-1;
$b=0;
while($element = current($test)) {
$key=key($array);
if($b!=$a){
$q.=$key."=".$test[$key]." and ";
}
else {
$q.=$key."=".$test[$key];
}
next($array);
$b=$b+1;
}
for this your array must contain columnname as key
for example
$test['name'],$test['lastname']
then it will return
$q="select * from table where name=testnamevalue and lastname=testlastnamevalue";
hope it works