Search database while I enter data in to a text area - javascript

I have a table data [Columns: id,question,answer each question have answer]; In frontend/UI i have a textarea while i paste a question to this field which search for exact question in db and show the result.
I want ajax no need to click any search button. I want this to work when I paste question in to the text area.
Code i am using
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS3</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>PHP5</h1>
<form class="form-inline">
<div class="form-group">
<input size="100" type="text" id="searchid" class="form-control" rows="10" cols="100" />
</div>
<div id="resultdiv"></div>
</form>
</div>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
</body>
</html>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#searchid').keydown(function (e){ // Event for enter keydown.
if(e.keyCode == 13){
var idvalue = $("#searchid").val(); // Input value.
$.ajax({ //Ajax call.
type: "GET",
url: "search.php",
data: 'id=' + idvalue ,
type: 'json',
success: function(msg){
// Show results in textareas.
msg = JSON.parse( msg ); // Line added
alert (msg);
$('#resultdiv').val(msg.answer);
}
}); // Ajax Call
} //If statement
}); //document.ready
</script>
My Search.php
<?php
if ($_GET['id']):
$dataid = json_decode($_GET['id']);
// Connect to database.
$con = mysqli_connect("localhost","root","");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
$sql = "SELECT answer FROM exam_css3 where question LIKE '$dataid' ";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
?>
This code is not working, can anyone help on this?

There are, among other things, some issues in your PHP.
First of all you search for $dataid, which means an exact match. You need to do
"SELECT answer FROM exam_css3 where question LIKE '%{$dataid}' ";
Then you always save only one answer, and you do not specify quote marks around 'answer', which might cause a PHP warning, which would corrupt the JSON output:
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
So you might want to rewrite that as
<?php
if (array_key_exists('id', $_GET)) {
$dataid = json_decode($_GET['id']);
// Here it would be good to check whether the decoding succeeded.
// I'd also try doing in HTML: data: { id: idvalue }
// Connect to database.
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
// Only interested in one match.
$sql = "SELECT answer FROM exam_css3 where question LIKE '%{$dataid}%' LIMIT 1";
$result = mysqli_query($con,$sql);
$answer = mysqli_fetch_assoc($result);
if (null === $answer) {
$answer = array('answer' => 'nothing found', 'status' => 'error');
}
// Since we're putting this into HTML...
$answer['answer'] = HTMLspecialChars($answer['answer']);
} else {
$answer = array('answer' => 'no query was supplied', 'status' => 'error');
}
Header ('Content-Type: application/json');
die(json_encode($answer));
In the code above I have added a 'status' variable so that in the jQuery you can do
if (msg.error) {
alert("Error: " + msg.answer);
return;
}
and further differentiate between correct and incorrect answers.
Other issues exist (for example you ought to use PDO and switch to prepared queries; as things stand, if the question contains a quote sign such as
What's a SQL injection?
your SQL search would throw an error. This is not limited to SQL injection. NO QUERY CONTAINING QUOTE MARKS WILL WORK. You need at least to escape the string dataid before placing it in the query.

You are defining twice the type in your ajax. json is the dataType not simple the type. type is get, what you do not need to set, that is the default.
The second problem is, you pass your data as a string, not as a json object, so on your server side, that will be an array, what you can not json_decode.

Related

PHP SQL form with JS action - show result only in individual div instead of all

I need to echo the result of a dynamically created form post request only in one div.
The original table and scripts are more complex, but I broke it down to the basics for this example.
Table:
form.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
<style>
body {padding: 30px; font-family: Arial;}
input {margin: 6px 0;}
.result {margin-bottom: 30px; color:green;}
</style>
</head>
<body>
<?php
$conn = mysqli_connect('dbserver', 'dbuser', 'dbpw', 'dbname') or die("Connection failed: " . mysqli_connect_error());
$conn->query("SET NAMES 'utf8'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM table_name ORDER BY email ASC";
$rs_result = mysqli_query($conn, $sql);
//the following part will echo multiple individual forms, depending on the table content. In this case 5.
while ($row = mysqli_fetch_assoc($rs_result)) {
echo '
'.$row["email"].'
<form action="marked.php" method="POST" id="marked_form_'.$row["id"].'" class="marked_form">
<input type="hidden" name="email_to_mark" value="'.$row["email"].'">
<input type="submit" name="submit" value="Submit" class="marked_submit">
</form>
<div class="result">
<!--echo result here-->
</div>
';
}
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".marked_form").submit(function() {
// Getting the form ID
var formID = $(this).attr('id');
var formDetails = $('#'+formID);
$.ajax({
type: "POST",
url: 'marked.php',
data: formDetails.serialize(),
success: function (data) {
// Inserting html into the result div
$('.result').html(data);
},
error: function(jqXHR, text, error){
// Displaying if there are any errors
$('.result').html(error);
}
});
return false;
});
});
</script>
</body>
</html>
The code above will echo 5 forms in this example, looking like this:
The form is submitted to marked.php, which will return/echo the result:
<?php
$email_to_mark = $_POST['email_to_mark'];
$conn = new mysqli('dbserver', 'dbuser', 'dbpw', 'dbname');
$sql = "UPDATE table_name SET marked='1' WHERE email='$email_to_mark'";
if (mysqli_query($conn, $sql)) {
echo 'SUCCESS';
} else {
echo 'ERROR';
}
?>
In general the form and the request work fine, but when I submit one of the forms, the result will appear in all class="result" divs on the page, looking like this:
When I change it from
<div class="result">
to
<div id="result">
it shows the result only in the first div, even if it's not below the form I submitted it from.
==========================
So what I need is the result to be shown only below the form I just submitted, like simulated here:
My attempt would be to create individual result divs with individual ids with the help of the table ids, like...
<div id="result_'.$row["id"].'">
...but since I am a JS novice, I don't know how to individually write into these divs.
Thanks.
Try This,
Changed your form id
<form action="marked.php" method="POST" id="form_'.$row["id"].'" class="marked_form">
replace result div class as id and add unique $row id or concate it
<div id="result_form_'.$row["id"].'">
<!--echo result here-->
</div>
JS Changes
$(".marked_form").submit(function() {
// Getting the form ID
var formID = $(this).attr('id');
var formDetails = $('#'+formID);
$.ajax({
type: "POST",
url: 'marked.php',
data: formDetails.serialize(),
success: function (data) {
// Inserting html into the result div
$('#result_'+formID).html(data);//changes
},
error: function(jqXHR, text, error){
// Displaying if there are any errors
$('#result_'+formID).html(data);//changes
}
});
just updated your result div id
You should specify the corresponding id in js. For example:
HTML
<div id="result_'.$row["id"].'">
JS
$('#result_' + formID).html(data);
Have Very simple techniques is there
Just use .next() function
$(this).next().html(data);
OR
$(formID).next().html(data);

Creating a unique variable for data

Hi guys so i have created a simple comment box for my site now. It works perfectly, however the problem i am having is that i have different pages which are going to require different comment box. I cant seem to figure out how to get the comment box to be unique for every page. So right now my database holds this :
Called comments:
id
comment
comment1
comment_date
Now my idea is that everything was stored into comment, so i added comment1 for other page to store the info. However i have no clue how to edit the php file to get it to work with comment1. Any help on this would be great.
HTML:
<div class="comment_container">
<div class="comments">
<?php
include_once("comments.php");
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
JS:
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
$.post("comments.php?action=post", {
comment: $('#comment_text').val()
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
PHP:
include_once("connect.php");
function convert ($date) {
$converteddate = date("F j, Y g:ia", strtotime($date." +1day"));
return $converteddate;
}
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date ) VALUES ('".$comment."', now())");
return true;
}
if((isset($_GET['action'])) && ($_GET['action']== "post")){
postComments($_POST['comment']);
}
echo getComments();
Thanks again for the help
DISCLAIMER
For future visitors:
Don't copy this code, as it has several issues that go beyond answering the question.
What you need to add is an identifyer for the type of comment. (Type could be replaced with something more suitable to your case like 'product', 'user', ... whatever the difference is/what they are related to)
So in your database add that new column:
comments
--------
id
comment
type
comment_date
Now you need to pass around that type through all your calls, and it shall be specified in your 'HTML'-Page (which actually is php...).
<div class="comment_container">
<div class="comments">
<?php
// specify the type needed on that page
$type = 1;
include_once("comments.php");
echo getComments($type);
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
<script>
// specify the type in javascript
var type=1;
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
// add the type here:
$.post("comments.php", {
comment: $('#comment_text').val(),
type: type,
action: 'post'
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
</script>
and in comments.php:
//....some code left out here
function getComments($type){
$comments = "";
$sql = mysql_query("SELECT * FROM comments where type=$type") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment, $type){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date, type ) VALUES ('".$comment."', now(), ".$type.")");
return true;
}
if((isset($_POST['action'])) && ($_POST['action']== "post")){
postComments($_POST['comment'], $_POST['type']);
// send all the comments back to client
echo getComments($_POST['type']);
}
// moved to html-file: echo getComments($type);
NOTE
There are several issues with that code.
First don't use mysql functions. For real. Unsecure and deprecated/deleted as of php7. Use mysqli or pdo. Furthermore your sql can be hacked with sql injection. Read about prepared statements.
The general structure of that code is not very good.
Try to seperate output and formating from getting data.
For example it would be much better if a function called 'getComments' only would get the comments from the database, then let others decide what to do with that data. The less one function does the better.
Please read about coding styles, maybe start learning object oriented programming.
I hope this still helps you to get a clue of where to go!

how to solve "Uncaught SyntaxError: missing ) after argument list" error

I am working on putting a project and one part of project is retrieving all the data from excel cells into an array for autosuggestion jquery like the one in the autocomplete module link.
So far I achieved to put data from excel into PHP array than convert into JQuery array with help Json_encode and by using flattenArray function all my data is in a single dimensional Array.
Autocomplete function works when my data comes out of an basic excel data which looks like:
however when I put a little bit complicated data like this:
I face of with a problem Uncaught SyntaxError: missing ) after argument list when data goes exactly into my
$(function(){var availableTags = $.parseJSON('<?php echo json_encode($myFlatArray); ?>');
my question how can I prevent this error appearing and autocomplete works fine?
Edit:
here is my code...
<?php
set_include_path(implode(PATH_SEPARATOR, [
realpath(__DIR__ . '/Classes'), // assuming Classes is in the same directory as this script
get_include_path()
]));
require_once dirname(__FILE__) . '/Classes/PHPExcel/IOFactory.php';
require_once 'PHPExcel.php';
$file= "./uploads/".$_GET["filename"];
$inputFileName = ($file);
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
$total=array();
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// echo "-----------------as rowData---------------";
// var_dump($rowData); // Insert row data array into your database of choice here
// echo "-----------------VAR_DUMP total!---------------";
array_push($total, $rowData);
// var_dump($total);
$myFlatArray = PHPExcel_Calculation_Functions::flattenArray($total);
echo "<br>";
echo "----------------- KOVA as json encode---------------";
var_dump(json_encode($myFlatArray));
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function(){var availableTags = $.parseJSON('<?php echo json_encode($myFlatArray); ?>');
$( "#tags" ).autocomplete({source: availableTags});
});
</script>
</head>
<body>
<br>
<br>
<br>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
<br>
<br>
<br>
<br>
</div>
</body>
</html>

How do I add a filter to avoid the using of bad words?

I would like to add to this chat system a function which should avoid foul language. I already tried to implement the following code: How to block bad words upon form submit
But it didn't work for me, and maybe I didn't put it to the right position.
The bad words should get changed to a star word before the message before the message is put into the database.
Could someone please help me with the code and tell me what I could do?
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<?php
exit;
}
?>
<html>
<head>
<title>Chat Box</title>
<!-- Mobile Optimation -->
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="user-scalable=yes, width=device-width">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" type="text/css" href="chat.css" />
<script type='text/javascript' src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function submitChat(){
if(form1.msg.value == ''){
alert('Enter your message!');
return;
}
$('#imageload').show();
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
$('#imageload').hide();
}
}
xmlhttp.open('GET','insert.php?msg='+msg,true);
xmlhttp.send();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlogs').load('logs.php');}, 2000);
});
function pageScroll(){
$("html, body").animate({ scrollTop: $(document).height() }, "fast");
}
window.onload = function(){
setTimeout(function(){
$("html, body").animate({ scrollTop: $(document).height() }, "fast");
}, 4000);
};
</script>
</head>
<body>
<div class="header">
<div class="header_platz"></div>
<img src="png/home-50.png" class="header_home">
<span class="part_name">Globalchat</span>
<img src="png/info-50.png" class="header_info">
<span class="loggedin">Logged in as: <b><?php echo $_SESSION['username']; ?></b></span>
</div>
<div id="imageload" style="display:none;">
<img src="1-0.gif" />
</div>
<div id="chatlogs">
LOADING CHATLOGS PLEASE WAIT... <img src="1-0.gif" />
</div>
<div class="chatbox">
<form name="form1">
<input name="msg" id="mes_msg" class="boxformal boxformal-cf" required placeholder="Message"></input>
<input type="submit" style="visibility:hidden" onClick="submitChat();pageScroll()" class="button"></input>
Send
</form>
</div>
</body>
EDIT:
OK, this is the insert.php script:
#Jonathan Kuhn
<?php
session_start();
$uname = $_SESSION['username'];
$msg = $_REQUEST['msg'];
$con = mysql_connect("localhost", "--", "--");
mysql_select_db('chat',$con);
mysql_query("INSERT INTO logs (`username` , `msg`) VALUES ('$uname','$msg')");
$result1 = mysql_query("SELECT * FROM logs ORDER by id ASC");
while($extract = mysql_fetch_array($result1)){
echo "<span class='uname'>" . $extract['username'] . "</span>: <span class='msg'>" . $extract['msg'] . "</span><br>";
}
?>
Here is the new insert.php. I added the badword filter, switched it over to using mysqli (which will prevent sql injection) and secured it a little.
<?php
session_start();
$uname = $_SESSION['username'];
$msg = $_REQUEST['msg'];
$db = new mysqli("localhost", "user", "pass", "chat");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
//the list of words to check.
$badWordList = array(
'test1',
'test2'
);
//loop over each bad word
foreach($badWordList as $k=>$bad){
//clean up the bad word for use in a regex
$pattern = '/\b'.preg_quote($bad).'\b/i';
//replace each bad word
$msg = preg_replace($pattern, str_repeat('*', strlen($bad)), $msg);
}
//call html entities to prevent html from being entered
$msg = htmlentities($msg, ENT_QUOTES);
//create a prepared statement
$stmt = $db->prepare("INSERT INTO logs (`username` , `msg`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $msg);
//run the query to insert the row
$stmt->execute();
//get all the entries from `logs`
if($result = $db->query("SELECT `username`,`msg` FROM `logs` ORDER by `id` ASC")){
//loop over the result and echo out the chat
while($row = $result->fetch_assoc()){
echo "<span class='uname'>" . $row['username'] . "</span>: <span class='msg'>" . $row['msg'] . "</span><br>";
}
} else {
die("There was an error retrieving the chat records: " . $db->error);
}
Some notes:
This will find bad words in a case sensitive manner so if you were looking for "foo", it will find "FOO" or "Foo" or "fOo".
It is using a boundary match so it will match the whole word only. If you were looking for "foo", it would not match "food". Keep this in mind as it will also not match a plural version of a bad word. If you remove the \b boundary characters from the pattern then "food" will become "***d". Up to you how want to handle it.
It is easy to bypass. You can substitute characters ("f00" with zeroes), put additional characters ("foooo") or do something like add spaces between letters ("f o o"). It won't catch any of those variations.
This is meant as a simple first line detection. Nothing will substitute having someone moderate the chat and taking action. You can make your filter more advanced but that gets complicated and the tradeoff from simplicity isn't usually worth it.
//before send
var regex = /\b(please help me|bad words)\b/i;
msg = msg .replace(regex, "***");
//finally

Can't insert into database an autofill fields?

it's my first time asking here,
I've been trying to look for something similar in other questions asked, and couldn't find it.
I have a form with Zip code line(textbox) and State line(textbox),
now, the stateboxes are auto-filled by a javascript by entering a valid US zip code.
the form itself is a bit longer.
I only show the relevant code that has been edited by me,
It was a select menu before (and everything worked just fine - data was entered into databse), and I changed it, so no select will be needed.
There is also css file, but it's irrelevant (designing isn't the issue)
So, here is my html code :
<html>
<head>some content here</head>
<body>
<form method="post" action="process.php">
<div class="title"><h2>my form title</h2></div><br>
<div align="center" class="element-name">
</span>
<span align="center" id="zipbox" class="nameFirst">
<input type="text" class="medium" pattern="[0-9]*" name="col2" id="col2" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span>
<span align="center" id="zipbox2" class="nameLast">
<input type="text" class="medium" pattern="[0-9]*" name="col4" id="col4" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span></div>
<div align="center" class="element-name">
<span class="required"></span>
<span align="center" id="statebox" class="nameFirst">
<input type="text" class="medium" name="col1" id="col1" placeholder="" required />
<label class="subtitle">From</label>
</span>
<span align="center" id="statebox2" class="nameLast">
<input type="text" class="medium" name="col3" id="col3" placeholder="" required />
<label class="subtitle">To</label>
</span></div>
<p align="center"><input type="reset" value="Clear"></p>
</body>
</html>
some javescript !
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(document).ready(function() {
$("#col2").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city").val(result.city);
$("#col1").val(result.state);
}
});
}
});
});
</script>
<script>
$(document).ready(function() {
$("#col4").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city2").val(result.city);
$("#col3").val(result.state);
}
});
}
});
});
</script>
and php code to process the form :
- it's 13 columns, but i know for sure that the other values are correct.
- col0 represent the date.
<?php
require_once('recaptchalib.php');
$privatekey = "mycaptchakey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
$process = FALSE;
} else {
// Your code here to handle a successful verification // Your code here to handle a successful verification
}
define('CONST_SERVER_TIMEZONE', 'EDT');
define('CONST_SERVER_DATEFORMAT', 'YmdHis');
$current_date = date("Y-m-d H:i:s");
$col0 = $_POST['col0'];
$col1 = strtoupper($_POST['col1']);
$col2 = strtoupper($_POST['col2']);
$col3 = strtoupper($_POST['col3']);
$col4 = strtoupper($_POST['col4']);
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
$mode = "mysql";{
define ('DB_USER', 'uname');
define ('DB_PASSWORD', 'pass');
define ('DB_HOST', 'host');
define ('DB_NAME', 'dbname');
$dbc = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die('Failure: ' . mysql_error() );
mysql_select_db(DB_NAME) or die ('Could not select database: ' . mysql_error() );
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
$q = mysql_query($query);
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
//for testing only
//echo "<p>MySQL Insertion Successful</p>";
}}
header( 'Location: http://mywebsite.com/index.php' );
?>
i'm not sure if i'm doing it right but here is my
mytable structure :
1 - sid - int(11) AUTO_INCREMENT
2 - col0 - date
3 - col1 - text utf8_unicode_ci
4 - col2 - text utf8_unicode_ci
5 - col3 - text utf8_unicode_ci
6 - col4 - text utf8_unicode_ci
and so on up to 12 columons.
Help please ! what is going wrong here ?
EDIT :
Thank you very much r3wt for the usefull information,
there is a lot to fix especially when it comes to the php part of it :)
ok, so i was able to fix the insertion.
i missed a critical value -
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
should have been:
$query = "INSERT INTO mytable VALUES ('','$current_date','$col1','$col2','$col3','$col4')";
that's is because all this form info is going into a phpGrid table
and i had a hidden column 'sid' which is automatically beeing filled.
I promise that in the next time I will be prepare with some more knowledge :)
thanks again.
This waits until a second has past after they have finished typing in the element, then submits the ajax request.
$(function(){
$("#col4").keyup(function() {
var col4val = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){fillLocation(col4val)}, 1000);
});
var timer = null;
function fillLocation(value){
$.get('http://zip.elevenbasetwo.com', {zip: value} , function(data){
var result = JSON.parse(data);
$("#city2").val(result.city);
$("#col3").val(result.state);
});
}
});
also, your php code is considered to be woefully insecure because you are using mysql.
also, i just noticed a glaring error, you are missing and and operator between $col2 isset and $col3, check your ajax i guarantee you it is returning 500 internal server error:
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
also, your query is wrong. its obvious you are just copy and pasting things together here. go read the mysql manual on INSERT statements and go read up on the mysqli and pdo extensions for php.
A valid mysql statement looks like:
INSERT INTO mytable (column1,column2,column3) VALUES ('val1','val2','val3')
realizing this, you could construct the statement in php like so
$query = mysql_query("INSERT INTO mytable (column1,column2,column3) VALUES ('".$val1."','".$val2."','".$val3."')");
if you continue to use mysql you will get your site hacked, its just a matter of time, especially since you don't sanitize any of your data. please make the smart choice and use mysqli or pdo to interface with the database from php.
As per the request of Dikei, i'm going to introduce you briefly to prepared statements with mysqli so that you may learn to use safe methods for interacting with the database.
$mysqli = new mysqli('host','username','password','databasename');
$mysqli->set_charset("utf8");
$stmt = $mysqli->prepare("INSERT INTO mytable (column1,column2,column3) VALUES (?,?,?)");//bind your variables in the same order!
//s for a string, d for a double floating point integer, and i for unsigned int.
$stmt->bind_param('sss',$col1,$col2,$col3);
if($stmt->execute()) {
$row = $stmt->insert_id ?: null;
if(!empty($row))
{
//query success
}else{
//query failure
}
$stmt->close();
}
$mysqli->close();
if you need more info, i provided a broader example of working with mysqli using the Object Oriented approach here(its in part two of the answer): login session destroyed after refresh

Categories