I'm trying to insert data to a Wordpress database from a form using the post method. Beofre inserting (code will go where comment is) I'm trying to print the results to screen. When I test my code to collect this data from the form it errors only on one field for some reason. The others post correctly so I'm at a bit of a loss. Below is the code:
global $mydb;
echo '<form name="newProducts" method="post">';
$output = "<div>";
// array of column names
$table_name = $mydb->prefix . '`my-table-names`';
foreach ( $mydb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
if($column_name!='id'){
$table_name = $mydb->prefix . '`my-table-names`';
$field_name = $column_name;
$getSpecColNameOne = $mydb->get_var($mydb->prepare( "SELECT {$field_name} FROM {$table_name} WHERE id=%d", 0));
$output .= '<div>';
$output .= '<div>' . $getSpecColNameOne . '</div>';
$output .= '<div><input name="' . $column_name . '" type="text" value=""></div>';
$output .= '</div>';
}
}
$output .= '</div>';
echo $output;
$_POST = array_map( 'stripslashes_deep', $_POST );
echo '<div class="btnWrapper">';
echo '<input class="btn border-width-0 btn-text-skin btn-color-jevc btn-square btn-icon-left adduserBtn" type="submit" name="btnSubmit">';
echo '</form>';
if ($_POST) {
$skipKeys = array(
'btnSubmit',
'id',
);
foreach($_POST as $key =>$value){
if(!in_array($key,$skipKeys)){
///insert into db here////////
echo '</br>';
echo"Key:";
print_r ($key);
echo '</br>';
echo"value:";
print_r ($value);
}
}
}
The output I get if I don't fill out column_1 looks like this:
Key:column_1
value:
Key:column_2
value:Input Test 2
Key:column_3
value:Input Test 3
However, if I fill in data into column_1 input field it errors and I get redirected to a 404 page.
column_1 html output looks ok:
<input name="column_1" type="text" value="">
Any ideas appreciated.
Related
I have built a list (moviesSeen) where people can save their seen movies.
Now I want to get the director for each movie from an API and then compare which movies have already been seen. The output of the movies works without problems, but I can't get the result from the database (moviesSeen) to match the movies of the director. How can I achieve this?
The goal of the script is to show all movies of a director and mark all the ones you have already seen.
function getCrewDetails() {
global $apiKey;
global $language;
$personID = htmlspecialchars($_GET['personID']);
$url = "https://api.themoviedb.org/3/person/" . $personID . "?api_key=" . $apiKey . "&" . $language . "";// path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$personPrivate = json_decode($data); // decode the JSON feed
echo '<div class="row">';
echo '<div class="col">';
echo '<img src="https://image.tmdb.org/t/p/w300/' . $personPrivate->profile_path . '" class="img-thumbnail">';
echo '</div>'; // end div col
echo '<div class="col-8">';
echo '<h1>' . $personPrivate->name . '</h1>';
if (!empty($personPrivate->biography)) {
echo $personPrivate->biography;
} else {
echo '<p>Verdammmt! Zu dieser Person liegen keine biographischen Details vor.</p>';
echo '<p>Dabei hätte sie es doch so verdient :(</p>';
}
echo '</div>'; // end div col
echo '</div>'; // end div row
// echo '<pre>';
// print_r($person);
$url = "https://api.themoviedb.org/3/person/" . $personID . "/movie_credits?api_key=" . $apiKey . "&" . $language . "";// path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$personCareer = json_decode($data); // decode the JSON feed
echo '<div class="container mt-4">';
echo "<h2>Filmographie</h2>";
echo '<table class="table table-striped table-sm">';
echo '<thead>';
echo '<tr>';
echo '<th scope="col">Film</th>';
echo '<th scope="col">Gesehen</th>';
echo '<th scope="col">Funktion</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM movieSeen WHERE user_id = '" . $_SESSION['id'] . "'");
$stmt->execute();
foreach ($stmt as $row ) {
echo $row['movie_id'] . ', ';
} // output of the saved IDs in movieSeen
foreach ($personCareer->crew as $showCrewDetails) { //Output of the movies
echo '<tr>';
echo '<td>' . $showCrewDetails->title . ' ' . $showCrewDetails->id . ' (' . substr($showCrewDetails->release_date, 0, 4) . ')</td>';
echo '<td><span class="badge badge-danger">Movie Seen</span></td>';
echo '<td>' . $showCrewDetails->job . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
//echo '<pre>';
//var_dump($personCareer);
}
I know that I have to edit the last foreach loop, but I just can't get it to work :(
I've never run into this situation I'm having now. And am using this setup in another part of the site. I cannot figure out why I don't get any post data, my session variables never update.
Here is the html form, dynamically creating a row of check boxes:
$html .= '<form id="status_form">';
foreach ($leads as $key => $type) {
$html .= '<input type="checkbox" name"' . $key . '" id="' . $key . '" class="box_status" value="1"';
if (something = true) {
$html .= ' checked="checked"';
}
$html .= ' />';
$html .= '<label class="checkbox-inline" for"' . $key . '">' . $type . ' (' . #$count[$key] . ')</label>';
}
$html .= '</form>';
echo $html;
Each time a checkbox is checked, javascript is submitting the form to primarily update session variables and then reload the page:
function update_report() {
var form_data = $("#status_form").serialize();
$.ajax({
type: 'POST',
url: 'scripts/test.php',
data: form_data,
success: function() {
window.location.reload(true);
}
});
}
$('.box_status').change(function(){
update_report();
});
And here is the test.php file:
session_start();
if (isset ($_POST)) {
$_SESSION['crm']['reports']['index'] = array();
foreach ($_POST as $k => $v) {
$_SESSION['crm']['reports']['index'][] = $k;
}
$_SESSION['post'] = $_POST;
echo true;
}
I've double checked and the form is displayed correctly, the ajax makes the call, I've done "hello world" checks in test.php.. it even goes into the if(isset($_POST)) portion, but the session variables don't change, and if I assign $_POST to another session variable, it shows me nothing.
You have an error in your string concatenation:
$html .= '<input type="checkbox" name"' . $key . '" id="' . $key . '" class="box_status" value="1"';
name"' is supposed to be name="' You forgot the equal sign. jQuery serialize only takes input tags with names.
Your solution:
$html .= '<input type="checkbox" name="' . $key . '" id="' . $key . '" class="box_status" value="1"';
Note:
The best way to debug this sort of problem is to take a look at your generated html. When you load the page, check the page source. You also made the same error on your label tag.
I'm stuck on a piece of code that calls a jQuery modul populated with a table row id. I'm about 90% sure that the error is within my jQuery code. Once I click on the button (class="view"), I get an undefined value instead of the row ID.
Thanks for any help!
Relevant section of leads_queue_a.php:
<section class="main">
<h1>Lead Queue - Assigned Leads</h1>
<div id="lead_wrapper_a"></div>
</section>
fill_leads_a.php:
$cond = array();
$params = array();
if ($_POST['id'] == '') {
return;
}
if (isset($_POST['id']) && $_POST['id'] != '') {
$userID = $_POST['id'];
}
if (!empty($userID)) {
$cond[] = '`users`.`id` = ?';
$params[] = "$userID";
}
$query = "SELECT `leads`.`id`, `leads`.`fname`, `leads`.`lname`, `leads`.`lead_type`, `leads`.`addr_street`, `leads`.`addr_city`, `leads`.`addr_zip`, `leads`.`phone`, `leads`.`phone_alt`, `leads`.`note`, `leads`.`created_by`, `leads`.`created` FROM `leads`,`users`,`leads_assignment`";
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
$query .= ' AND `leads`.`id` = `leads_assignment`.`id_lead`'
. ' AND `users`.`id` = `leads_assignment`.`id_user`';
$stmt = $db->prepare($query);
$stmt->execute($params);
//TABLE BUILDER
$lead = '';
$lead .= '<div class="leads">';
$lead .= '<table class="lead_table">';
$lead .= '<tr>';
$lead .= '<td>Customer</td>';
$lead .= '<td>Phone</td>';
$lead .= '<td>Lead Type</td>';
$lead .= '<td>Status</td>';
$lead .= '<td>Operations</td>';
$lead .= '</tr>';
foreach ($stmt->fetchAll(PDO::FETCH_OBJ) as $row) {
$id = $row->id;
$status = get_statusLast($id);
$fname = $row->fname;
$lname = $row->lname;
$lead_type = $row->lead_type;
$addr_street = $row->addr_street;
$addr_city = $row->addr_city;
$addr_zip = $row->addr_zip;
$phone = $row->phone;
$phone_alt = $row->phone_alt;
$note = $row->note;
$created_by = $row->created_by;
$created = $row->created;
$lead .= "<tr id='$id'>";
$lead .= '<td>' . $fname . ' ' . $lname . '<br />' . $addr_street . '<br />' . $addr_city . ' ' . $addr_zip . '</td>';
$lead .= '<td>' . $phone . '<br />' . $phone_alt . '</td>';
$lead .= '<td>' . $lead_type . '</td>';
$lead .= '<td>' . $status . '</td>';
$lead .= '<td><button type="button" class="view" name="view">View Notes</button><br />'
. '<button type="button" class="update" name="update">Update Status</button></td>';
}
$lead .= '</table>';
$lead .= '</div>';
$db = null;
print $lead;
Relevent section of modul.js:
$("#lead_wrapper_a").on('click', '.view', function() {
alert($('tr', this).attr('id'));
});
Because your selction is incorrect. Use closest to get to the clicked buttons parent row (tr). Using the syntax $('tr', this) you are trying to find tr that are descendant of the button .view which is incorrect. You need to go upwards to get to the tr. this in the handler will be the button.
alert($(this).closest('tr').attr('id'));
You are trying to search row tr in descendant of button but button is descendant of row tr. You probably need closest() to get the ancestor row, to get the parent row of button having class view.
$("#lead_wrapper_a").on('click', '.view', function() {
alert($(this).closest('tr').attr('id'));
});
You cant find tr within the context of this, Because tr is the ancestor of the source button in your case. So you have to use .closest() to achieve the desired result.
Try,
$("#lead_wrapper_a").on('click', '.view', function() {
$( "#dialog_view" ).dialog( "open" );
alert($(this).closest('tr').attr('id'));
});
when it comes to table its bit tricky.
for your first line you want to select the entire path of class "view". I dont know your exact path but it should be someting like this.
$("#lead_wrapper_a").on('click', '"#lead_wrapper_a > table > tbody > tr > td.view', function() {
});
Hope this helps
In CodeIgniter, I'm trying to create a table which fills with data from the Facebook Graph API.
The JSON loads a controller which passes data to a view, and it is this view which is added to a pre-existing table.
My PHP view looks like this:
if (array_key_exists('is_community_page', $json)==FALSE){
echo '<tr>';
echo '<td>ID</td>';
echo '<td><a href="' . $json['link'] . '">'. $json['name'] .'</td>';
if (!empty($json['website'])) {
if (!preg_match("~^(?:f|ht)tps?://~i", $json['website'])) {
$json['website'] = "http://" . $json['website'];
}
echo '<td>' . $json['website'] . '</td>';
}
else {
echo '<td>N/A</td>';
}
if (!empty($json['likes'])) {
echo '<td class="num">' . number_format($json['likes']) . '</td>';
}
if (!empty($json['checkins'])) {
echo '<td class="num">' . number_format($json['checkins']) . '</td>';
}
echo '</tr>';
}
And the jQuery/JSON looks like this:
$.ajax({
url: "<?php echo site_url('controller/function'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#results_table').html(data);
}
});
But when the data is returned, it just inserts the <a> elements between the <table> tags, and none of the <td> or <tr>.
Can anyone see why it might be ignoring the table row and table data tags, yet still keeping anchor tags and all the desired content?
Have you tried print_r($json) before the if to see if you're getting any output whatsoever from the Facebook data?
As per the comments, adding <tbody> to the table seemed to fix this adequately.
Perhaps try appending markup to a string and return the final value?
$row_data = '';
if (array_key_exists('is_community_page', $json)==FALSE){
$row_data .= '<tr>';
$row_data .= '<td>ID</td>';
$row_data .= '<td><a href="' . $json['link'] . '">'. $json['name'] .'</td>';
if (!empty($json['website'])) {
if (!preg_match("~^(?:f|ht)tps?://~i", $json['website'])) {
$json['website'] = "http://" . $json['website'];
}
$row_data .= '<td>' . $json['website'] . '</td>';
} else {
$row_data .= '<td>N/A</td>';
}
if (!empty($json['likes'])) {
$row_data .= '<td class="num">' . number_format($json['likes']) . '</td>';
}
if (!empty($json['checkins'])) {
$row_data .= '<td class="num">' . number_format($json['checkins']) . '</td>';
}
$row_data .= '</tr>';
return $row_data;
}
i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.
Fine,
this is when i print the form
function imprimir_formulario_pregunta(){
$html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
$html .= '<h2>Pregunta</h2>';
$html .= '<input name="q" id="q" type="text" value=" "></input>';
$html .= '<h2>Explica tu duda</h2>';
$html .= '<textarea name="texto" id="texto" /
></textarea>';
$html .= '<h2>Etiquetas (separadas por comas)</h2>';
$html .= '<input name="tags" id="tags"/>';
$html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';
$html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';
$html .= '</form>';
echo $html;
}
this is when i recive data
if(isset($_POST['pregunta'])){
$p_title = $_POST['q'];
$p_text = $_POST['texto'];
$p_et = $_POST['etiquetas'];
$p_resp = $_POST['responde_a'];
post_pregunta($p_title,$p_text, $p_et, $p_resp);
this is when i process data
function obtener_id_pregunta($p,$t){
$consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
while($item = mysql_fetch_array($consulta)){
return $item['id'];
}
}
function post_pregunta($a,$t,$et,$r){
mostrar_notificacion("hemos entrado");
//// ******
if($a != '' && $t != ''){
$b = $a;
guardar_pregunta($b,$t,$r);
$id = obtener_id_pregunta($b,$t);
$temp = new etiqueta(0, '');
$basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);
}else
mostrar_notificacion("hemos salido $a $t");
}
function guardar_pregunta($p,$t,$r){
$id_tmp = $_SESSION['id'];
$insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
$qry = mysql_query($insert);
if(mysql_affected_rows())
{
mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
return true;
}
else
{
mostrar_notificacion("Error Ingresando datos");
return false;
}
return false;
}
Result:
I get the insert in the database done, but the 'q' field has a '' value....
Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...
Please tell me you have my answer, been too long on this.. and i need it done this week for class
Thanks in advance
It's hard to see what's going on - as #vincebowdren says, you just need to debug this every step of the way.
However, more worryingly you're using $_POST data directly in a SQL query - this is an SQL injection attack waiting to happen.
Ensure you wrap ALL such variables in a mysql_real_escape_string function within your queries.
e.g.:
$insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('".mysql_real_escape_string($p)."','".mysql_real_escape_string($t)."','$id_tmp',NOW(),'".mysql_real_escape_string($r)."')";
See How can I prevent SQL injection in PHP? for more information.
Use echo to print out the value of the troublesome variable ($_POST['q'], $p_title, $a) at every stage. Then you will see when it gets a value you weren't expecting.
#Toni Michel Caubet: I rewrote your code a little to make it more readable and should be slightly easier to debug as well. Please heed the /* comments */. I've left a lot of the work up to you with just some guides here and there.
Receive data:
if(isset($_POST['pregunta']))
{
$p_title = $_POST['q'];
$p_text = $_POST['texto'];
$p_et = $_POST['tags'];
$p_resp = $_POST['responde_a'];
/* Never trust user input, validate the data you're retrieving */
/* Keep variable names the same, or risk confusing yourself later */
post_pregunta($p_title, $p_text, $p_et, $p_resp);
}
Process data:
function post_pregunta($p_title, $p_text, $p_et, $p_resp)
{
mostrar_notificacion("hemos entrado");
/* You should handle validation like this after initially receiving post
data, the ideal would be to validate the data in a central location
and then only pass the valid data on to other functions to avoid
having to recheck everything.
*/
if($p_title != '' && $p_text != '')
{
guardar_pregunta($p_title, $p_text, $p_resp);
$id = obtener_id_pregunta($p_title, $p_text);
$temp = new etiqueta(0, '');
$basura = $temp->guardar_etiquetas($p_et, $id, $_SESSION['id']);
}
else
{
mostrar_notificacion("hemos salido $p_title $p_text");
}
}
function obtener_id_pregunta($p_title, $p_text)
{
/* This query may also be susceptible to SQL injection */
$consulta = mysql_query("SELECT id FROM preguntas WHERE pregunta='" . $p . "' AND texto='" . $t . "'");
while($item = mysql_fetch_array($consulta))
{
return $item['id'];
}
}
function guardar_pregunta($p_title, $p_text, $p_resp)
{
$id_tmp = $_SESSION['id'];
/* This query is susceptible to SQL injection not least because there's
no data validation. */
$insert = "INSERT INTO preguntas (pregunta, texto, id_usuario, fecha, responde_a) VALUES ('$p_title', '$p_text', '$id_tmp', NOW(), '$p_resp')";
$qry = mysql_query($insert);
if(mysql_affected_rows())
{
mostrar_notificacion("La pregunta $p_title ($p_text)($p_resp) se guardo");
return true;
}
else
{
mostrar_notificacion("Error Ingresando datos");
return false;
}
return false;
}
Print form:
function imprimir_formulario_pregunta()
{
$html = '<form id="preguntas" name="preguntas" method="post" action="preguntas.php">' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <h2>Pregunta</h2>' . "\n";
$html .= ' <input name="q" id="q" type="text" />' . "\n";
$html .= ' </div>' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <h2>Explica tu duda</h2>' . "\n";
$html .= ' <textarea name="texto" id="texto"></textarea>' . "\n";
$html .= ' </div>' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <h2>Etiquetas (separadas por comas)</h2>' . "\n";
$html .= ' <input name="tags" id="tags" />' . "\n";
$html .= ' </div>' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <input name="responde_a" style="display:none;" id="responde_a" value="0" />' . "\n";
$html .= ' <button name="pregunta" id="pregunta" type="submit">Publicar</button>' . "\n";
$html .= ' </div>' . "\n";
$html .= '</form>' . "\n";
echo $html;
}