I made a post array when i print it,I am getting following output.
Array
(
[name] => gowtham
[content] => Nice Website
)
where Key of array is a column name in my database and value is value in database.
i want to update my database using these values,but these values in post array changes basing on html form.
i made a string using implode.
$query ="UPDATE ".$_SESSION['table']." SET ".implode(' = ',$array);
but my output is
UPDATE testimonials SET gowtham = Nice Website
i want output as
UPDATE testimonials SET name = gowtham , content = Nice Website
Please help me
This approach is very insecure. I would recommend using a db class that handles this stuff for you....I use the following : http://www.imavex.com/php-pdo-wrapper-class/
try this way
$cols=array_keys($yourarray);
$cols=array_values($yourarray);
$colnames = "`".implode("`, `", $cols)."`";
$colvals = "`".implode("', '", $vals)."`";
$query="update tablename set ($colnames) values ($colvals)";
Something like this
$update = '';
$i = 0;
foreach ( $_POST as $key => $value ) {
$update = $key . ' = "' . $value . '"' . ( $i == count( $_POST ) ? ', ' : '' );
$i++;
}
$query ='UPDATE ' . $_SESSION['table'] . ' SET ' . $update;
Worth noting you may need to unset the submit button before you run the loop and if you need to update by an id you need to skip that in the loop and for the where clause separately, in a if statement would probably be easiest.
Also worth mentioning your should try and use PDO's or mysqli because the mysql_* functions in PHP are depreciated as of version 5.5.
PS - I know I didnt sanitise any of the data but you should!
Related
I have code that generalizes building the SQL string to insert a record into a table by (1) setting the 'name' of the form element to be the same as the table column to which it corresponds, and (2) building an array of field name => value pairs. I do it like this:
$fldArray = array();
foreach($_POST as $field => $value) {
$fldArray[$field] = $value; //create a field => value array
}
This allows me to build the SQL statement easily like this:
$visit_SQL = "INSERT INTO visits (";
foreach ($fldArray as $key => $value) {
$flds .= ($key) . ", " ; // sets up all the field names.
I then do something similar to generate the 'VALUES' part of the SQL statement. I then need only to add the provider_id info
$visit_SQL = $visit_SQL . "provider_id, " . $flds . ") VALUES (" . $user_ID . ", " . $vals . ")";
The reason I go about it this way is that there are a large number of Yes/No checkboxes on the form so it saves typing errors etc.
This works well except for two text inputs that require "$mysqli->escape_string(['field_name']) to deal with apostrophes etc. before inserting into the database.
I proved that the following works for explicit field names,
$test = $mysqli->escape_string($_POST['visit_notes']);
print_r($test) ;
However, I cannot generalize it into this statement (from above):
foreach($_POST as $field => $mysqli->escape_string($_POST[$value])) {
$fldArray[$field] = $value;
}
I'd appreciate knowing if I have a syntax error or if what I'm seeking is not possible.
Thanks in advance for any helpful responses.
You don't put the function call in the foreach header, you do it in the body.
foreach($_POST as $field => $value) {
$fldArray[$field] = $mysqli->escape_string($value);
}
I have researched several related question in this forum and google, Kindly assist . I am trying to insert some values into database from several arrays stored in session. I also have some single values stored in some session also which i want to insert into multiple rows of dbase table.
//First, I recall the values stored in sessions from previous pages into the current page as below.
//take note of the comment in front of the sessions and All array contains the same number of values except for the first two sessions.
$ticketid="t".date('dmyHis').mt_rand (1000,9999);
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;//Not array, contains single value
$_SESSION['ticketid']=$ticketid;//Not array, Contains single value
$_SESSION['gamecode'];//array
$_SESSION['starttime'];//array
$_SESSION['optioncode']//array
$_SESSION['home'];//array
$_SESSION['away'];//array
$_SESSION['odd'];//array
Here, I connected to dbase. //Works fine.
require('gumodb.php');
Here i try to start a loop using one array session as key
foreach($_SESSION['starttime'] as $ro => $col){
mysql_query("INSERT INTO reg_bet (bettime, ticketid,matchcode,starttime,home,away,optionodd,optioncode) VALUES('$_SESSION[bettime]','$_SESSION[ticketid]','$_SESSION[gamecode]', '$_SESSION[starttime]','$_SESSION[home]','$_SESSION[away]','$_SESSION[odd]','$_SESSION[optioncode]' ) ")
or die(mysql_error());
}
It returns Notice: Array to string conversion in C:\xampp\htdocs\gumo\consel.php on line 61
EDIT QUESTION
I am trying to achieve something like this.
foreach($_SESSION['gamecode'] as $gc => $gcvalue && $_SESSION['starttime'] as $st =>$stvalue && $_SESSION['optioncode'] as $oc => $ocvalue ){
mysql_query("INSERT INTO reg_bet (matchcode,starttime,optioncode) VALUES('$gcvalue','$stvalue','$ocvalue') ")
or die(mysql_error()); }
$x = json_encode($_SESSION);
$query = "INSERT INTO ".$TABLE_NAME data "VALUES ("$x");";
$mysqli->query( $query );
Encode the session array into a single string and insert in to the table on a row of data.
When you fetch the same data use json_decode to convert the string into array.
Assuming the arrays in the $_SESSION variable are numeric, you could try something like this:
for ($i = 0; $i < $max_index_count; $i++) {
$query = "INSERT INTO ".$TABLE_NAME;
$query += "VALUES (".$_SESSION['index'][$i].");";
$mysqli->query( $query );
}
The above is pseudo code, but the problem is you are trying to use an array as a string. The $_SESSION variable is a multidemsional array, therefore, specify two ibdexes.
After so many trials, i was able to get it done with this
$ticketid="t".date('dmyHis').mt_rand (1000,9999);//ticket id generateed
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;
$_SESSION['ticketid']=$ticketid;
$_SESSION['gamecode'];
$_SESSION['starttime'];
$_SESSION['optioncode'];
$_SESSION['home'];
$_SESSION['away'];
$_SESSION['odd'];
require('gumodb.php');
foreach ($_SESSION['gamecode'] as $index => $value)
{
$ge = $_SESSION['gamecode'][$index];
$se = $_SESSION['starttime'][$index];
$oe = $_SESSION['optioncode'][$index];
$he = $_SESSION['home'][$index];
$ay = $_SESSION['away'][$index];
$od = $_SESSION['odd'][$index];
This post the arrays and non array into table row and display
mysql_query("INSERT INTO reg_bet (matchcode,ticketid,bettime,starttime,home,away,optionodd,optioncode) VALUES('$ge','$ticketid','$bettime','$se','$he' ,'$ay','$od' ,'$oe' ) ")
or die(mysql_error());
echo $_SESSION['gamecode'][$index] .'-'. $_SESSION['starttime'][$index].'- '. $_SESSION['optioncode'][$index].' -'. $_SESSION['home'][$index].'- '. $_SESSION['away'][$index].'- '. $_SESSION['odd'][$index].$bettime.' -' .$ticketid.'</br>' ;
}
Thanks for your contributions.
Got a small problem regarding saving my form to the database and imploding. The issue is as following:
I have a form which has multiple fields, including checkboxes, which has an array of values. If I send the whole form to my php script it strips the checkbox value with the last one checked, so the issue is, I only get the last checked value in my database instead of all the checked values.
So I did a bit of debugging and I found the issue, it's in this line:
$values = "'" . implode("', '", $_POST) . "'";
This strips my data unfortunately.
EDIT:
This is my PHP script:
$hoeveelheidvalues = count($_POST);
$values = "'" . implode("', '", $_POST) . "'";
$queryvoorderesperform = "INSERT INTO `app_res_per_form` (";
for($i = 1; $i <= $hoeveelheidvalues; $i++)
{
if($i==$hoeveelheidvalues)
{
$queryvoorderesperform .= "vraag$i";
}
else{
$queryvoorderesperform .= "vraag$i, ";
}
}
$queryvoorderesperform .= ") VALUES ($values)";
EDIT 2:
If I use serialize I get a very weird string. This is the $queryvoorderespform:
INSERT INTO `app_res_per_form` (vraag1, vraag2, vraag3, vraag4, vraag5, vraag6, vraag7, vraag8, vraag9, vraag10, vraag11, vraag12)
VALUES (a:12:{s:16:"multipleradios-0";s:11:"Orientation";s:11:"textinput-0";s:0:"";s:20:"multiplecheckboxes-0";s:9:"Recycling";s:11:"textinput-1";s:0:"";s:10:"interestin";s:15:"Diverter Valves";s:12:"rotaryvalves";s:7:"AL, AXL";s:14:"divertervalves";s:3:"PTD";s:15:"othercomponents";s:3:"DUC";s:11:"textinput-3";s:0:"";s:16:"multipleradios-1";s:18:"Systems Integrator";s:16:"multipleradios-2";s:38:"Will buy product in long time (1 year)";s:15:"standcrewmember";s:13:"Aap";})
You can use serialize(), its a PHP function to convert an array or object into a string that can then be re-hydrated back into an array or object using unserialize();
$values = serialize($_POST);
or better still save the contents of $_POST as JSON using
$values = json_encode($_POST);
and re-hydrate into an array or object using
$var = json_decode($x);
These can be used on PHP Arrays or PHP Objects.
Ok now I see what you are actually trying to do so try this :-
$fields = '';
$values = '';
$count = 0;
foreach ( $_POST as $idx => $val ) {
// I assume you are skipping occurance 0 for a reason
if ( $count == 0 ) {
$count++;
continue;
}
$fields .= sprintf('vraag%d,', $count );
$values .= sprintf("'%s',", $val );
$count++;
}
//trim off trailing commas
rtrim($fields, ',');
rtrim($values, ',');
$sql = sprintf('INSERT INTO `app_res_per_form` (%s) VALUES (%s)',
$fields, $values);
}
Oh and I assume you are using the MYSQL_ extension! Someone is going to tell you not to and to switch to MYSQLI_ or PDO. So it may as well be me.
I have the following code (SQL-query tested in phpMyAdmin and seems to work) that fetch data from selected columns:
$ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : array();
if (is_array($ids)) $ids = implode(',', $ids);
if (!empty($ids)) {
$sql = "SELECT upload, upload2, upload3, upload4, upload5 FROM wp_site_table WHERE cid IN($ids) ORDER BY FIELD(cid, $ids)";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ) { ... } }
The problem I have is that I want to output all fields from selected cid.
This code will only display the first cid result.
echo $result->upload;
Let's say $ids contain cid 1, 4 and 7 I'd like to output upload, upload2, upload4, upload5 from all those specific rows. How? Use an array in some way?
kind regards
Johan
If you want to echo all the fields, just do it:
echo $result->upload . '<br>' . $result->upload2 . '<br>' . $result->upload3 .
'<br>' . $result->upload4 . '<br>' . $result->upload5;
You should perhaps consider redesigning your database so you don't have repeated fields in each row. It would be better to have another table where each upload is in a row of its own, so there's no hard-coded limit on the number of these values. Then you can use a JOIN query to get all the uploads, and they'll be in an array.
With '$wpdb->get_results' output defaults to OBJECT type. Try using pre defined constant : ARRAY_A , it will result the output as an associative array.
$sql = "SELECT upload, upload2, upload3, upload4, upload5 FROM wp_site_table WHERE cid IN($ids) ORDER BY FIELD(cid, $ids)";
$results = $wpdb->get_results($sql, ARRAY_A) or die(mysql_error());
To access, simply use :
foreach( $results as $result ){
echo $result['upload'];
}
I am trying to be lazy (or smart): I have 7 checkboxes which correlate with 7 columns in a MySQL table.
The checkboxes are posted in an array:
$can = $_POST['can'];
I've created the following loop to dump the variables for the MySQL insert:
for($i=1;$i<8;$i++){
if($can[$i] == "on"){
${"jto_can".$i} = 'Y';
}
else{
${"jto_can".$i} = 'N';
}
}
print_r($jto_can1.$jto_can2.$jto_can3.$jto_can4.$jto_can5.$jto_can6.$jto_can7);
This correctly outputs:
YYNYYYY
However, when I attempt to use those variables in my MySQL update, it doesn't accept the changes.
mysqli_query($db, "UPDATE jto SET jto_can1 = '$jto_can1', jto_can2 = '$jto_can2', jto_can3 = '$jto_can3', jto_can4 = '$jto_can4', jto_can5 = '$jto_can5', jto_can6 = '$jto_can6', jto_can7 = '$jto_can7' WHERE jto_id = '$id'")or die(mysqli_error($db));
Can anyone explain why the print_r displays the variables whereas MySQL update does not?
Stick with the array, and form the query dynamically:
$sql = 'UPDATE jto SET ';
$cols = array();
foreach( range( 1, 7) as $i) {
$value = $_POST['can'][$i] == 'on' ? 'Y' : 'N'; // Error check here, $_POST['can'] might not exist or be an array
$cols[] = 'jto_can' . $i . ' = "' . $value . '"';
}
$sql .= implode( ', ', $cols) . ' WHERE jto_id = "' . $id . '"';
Now do a var_dump( $sql); to see your new SQL statement.
this is not a mysql problem. mysql will only see what you put into that string. e.g. dump out the query string BEFORE you do mysql_query. I'm guessing you're doing this query somewhere else and have run into scoping problems. And yes, this is lazy. No it's not "smart". you're just making MORE work for yourself. What's wrong with doing
INSERT ... VALUES jto_can1=$can[0], jto_can2=$can[1], etc...