HTML form - PHP not inserting into Database correctly - php

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;
}

Related

Issues posting data

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.

function only returns one value multiple times

I have this function:
function get_content($text_to_match) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
But when I call it like:
<div>
<?php
for ($i = 1; $i < count(get_content("text_to_match")); $i++) {
echo '<article>' .
'<h3>' . get_content("text_to_match")["string1"] . '</h3>'.
'<p>' . get_content("text_to_match")["string2"] . '</p>' .
'</article>';
}
?>
</div>
I only get the first match in the DB repeated as many times as the number of found items.
Where have I gone wrong?
use this code then fetch data properly
while($content = mysql_fetch_array($cont))
{
return $content;
}
Your logic is at fault. You are calling get_content function to get all matches for the loop, as well as to get individual elements out of the list. This is:
bad logic - the 2nd use case doesn't make sense
excessive - you shouldn't need to run a database query just to output an already retrieved result
What you probably want to do is:
foreach (get_content('text_to_match') as $content) {
echo '<article>';
echo '<h3>' . $content['string1'] . '</h3>';
echo '<p>' . $content['string2'] . '</p>';
echo '</article>';
}
With a few modifications in combination with tips from #Anant and #Unix One's answer, I arrived at this working solution:
Function definition
function get_content($text_to_match, $multiple=false) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if ($multiple) {
$content_array = [];
while($content = mysqli_fetch_array($cont)) {
$content_array[] = $content;
}
return $content_array;
} else {
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
}
Function calls
<?php
/* multiple items */
foreach(get_content("text_to_match", true) as $content) {
echo '<article>' .
'<h3>' . $content["string1"] . '</h3>' .
'<p>' . $content["string2"] . '</p>' .
'</article>';
}
?>
<?php
/* one item */
echo get_content("text_to_match")["string"];
?>

Trying to change statement so create_radio function is only called once (PHP)

I have a function that creates a radio button in PHP:
// This function creates a radio button.
// The function takes two arguments: the value and the name.
// The function also makes the button "sticky".
function create_radio($value, $name = 'gallon_price')
{
// Start the element:
echo '<input type="radio" name="' .
$name .'" value="' . $value . '"';
// Check for stickiness:
if (isset($_POST[$name]) && ($_POST[$name] == $value))
{
echo ' checked="checked"';
}
// Complete the element:
echo " /> $value ";
} // End of create_radio() function.
I then leave the PHP form to create an html form and call the function three times with values that represent three different gas prices.
<span class="input">
<?php
create_radio('3.00');
create_radio('3.50');
create_radio('4.00');
?>
</span>
I am wondering how I could change this code so it would be possible to get the same output and only make one call to the create_radio function.
Thanks!
function create_radio($value, $name = 'gallon_price')
{
$output = "";
if (is_array($value)) {
while (count($value) > 0) {
$arr_value = array_pop($value);
$output .= create_radio($arr_value);
}
} else {
// Start the element:
$output .= '<input type="radio" name="' .
$name .'" value="' . $value . '"';
// Check for stickiness:
if (isset($_POST[$name]) && ($_POST[$name] == $value))
{
$output .= ' checked="checked"';
}
// Complete the element:
$output .= " /> $value ";
}
return $output;
}
A quick bit of recursion will allow the function to work for arrays and non arrays. Note: in the html you will need to echo the call to create_radio not just call it.
you could make $value an array create_radio(array('3.00','3.50','4.00')); just loop inside the function:
function create_radio($value,$name = 'gallon_price'){
foreach($value as $v){
// Start the element:
$out. = '<input type="radio" name="'.$name.'" value="'.$v.'"';
// Check for stickiness:
if(isset($_POST[$name])&&($_POST[$name]==$v)){
$out .= ' checked="checked"';
}
// Complete the element:
$out .= " /> $v ";
}
return $out;
} // End of create_radio() function.
call it:
echo create_radio(array('3.00','3.50','4.00'));
it is usually better not to echo inside the function.

Table Row attr() Issue

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

Module not showing on Joomla page (regular menu item)

I have a Joomla template that does not show a module on one of my pages. The module is published and is assigned to a regular published menu item.
After doing some research I found that the issue may be due to template overides. Here is my module.php file...is there anything in here that would cause a module not to show on a particular page?
Thanks,
<?php
defined('_JEXEC') or die;
function modChrome_themeHtml5($module, &$params, &$attribs) {
$moduleTag = $params->get('module_tag');
$headerTag = htmlspecialchars($params->get('header_tag'));
$headerClass = $params->get('header_class');
$bootstrapSize = $params->get('bootstrap_size');
$moduleClass = !empty($bootstrapSize) ? ' span' . (int) $bootstrapSize . '' : '';
$moduleClassSfx = htmlspecialchars($params->get('moduleclass_sfx'));
if (!empty ($module->content)){
$html = "<{$moduleTag} class=\"moduletable {$moduleClassSfx} {$moduleClass}\">";
if ((bool) $module->showtitle){
$html .= "<{$headerTag} class=\"moduleTitle {$headerClass}\">{$module->title} </{$headerTag}>";
}
$html .= $module->content;
$html .= "</{$moduleTag}>";
echo $html;
}
}
function modChrome_html5nosize($module, &$params, &$attribs){
$moduleTag = $params->get('module_tag');
$headerTag = htmlspecialchars($params->get('header_tag'));
$headerClass = $params->get('header_class');
$bootstrapSize = $params->get('bootstrap_size');
//$moduleClass = !empty($bootstrapSize) ? ' span' . (int) $bootstrapSize . '' : '';
$moduleClassSfx = htmlspecialchars($params->get('moduleclass_sfx'));
if (!empty ($module->content)){
$html = "<{$moduleTag} class=\"moduletable {$moduleClassSfx}\">";
if ((bool) $module->showtitle){
$html .= "<{$headerTag} class=\"moduleTitle {$headerClass}\">{$module->title}</{$headerTag}>";
}
$html .= $module->content;
$html .= "</{$moduleTag}>";
echo $html;
}
}
function modChrome_modal($module, &$params, &$attribs){
$moduleTag = $params->get('module_tag');
$headerTag = htmlspecialchars($params->get('header_tag'));
$headerClass = $params->get('header_class');
$bootstrapSize = $params->get('bootstrap_size');
// $moduleClass = !empty($bootstrapSize) ? ' span' . (int) $bootstrapSize . '' : '';
$moduleClassSfx = htmlspecialchars($params->get('moduleclass_sfx'));
if (!empty ($module->content)){
$html = "<div class=\"modal fade moduletable {$moduleClassSfx} loginPopup\" id=\"modal\">";
$html .= "<button type=\"button\" class=\"close modalClose\">×</button>";
if ((bool) $module->showtitle){
$html .= "<div class=\"modal-header\">";
$html .= "<{$headerTag} class=\"{$headerClass}\">{$module->title}</{$headerTag}>";
$html .= "</div>";
}
$html .= "<div class=\"modal-body\">";
$html .= $module->content;
$html .= "</div>";
$html .= "</{$moduleTag}>";
echo $html;
}
}
It might be if (!empty ($module->content))
We can't be so sure from just looking at the code. Try debugging it yourself by commenting out the code inside functions part by part, and see from which function the problem is occurring. That's the easiest and fastest way.

Categories