im using checkfile to upload file by Month & Year .
If success it will load the data to database.
IF checkfile = false
I want to display an alert message ("import Fail")
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
echo "Import $value successfully! <br>" ;
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
unset($value);
?>
I tried to have echo alert('Import Fail ');
but it give me multiple alert every single file from the folder .
Way1 : Manage the flow with flag as below. If any of the file successfully imported then change the flag and then make a condition on the flag to display alert.
$flag = 0;
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
$flag = 1;
echo "Import $value successfully! <br>" ;
// $query1 =
// "Delete FROM hklcanet_pha.psr this
// WHERE year(psr.ReportDate) = $input3
// AND month(psr.ReportDate) = $input2";
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
into table hklcanet_pha.psr fields terminated by ','
optionally enclosed by '\"'
lines terminated by '\n'
ignore 1 lines
(`ReportDate`, #dummy, #dummy, `Team_refno`,`Name/Description`,`Status`,`PIC`,`RequestDate`,`TargetEndDate`,`ActualEndDate`,`PlanStartDate`,`ActualStartDate`,`PlanUATDate`,`ActualUATDate`,`PlanImplement`,`ActualImplement` )";
//echo "Import $value successfully! <br>" ;
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
if($flag == 1){
echo "<script>alert('Import Fail ');</script>";
}
unset($value);
?>
Way 2: Get the name of successfully imported file names and make conditions on it.
$flag = [];
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
//Store successful file names in array
$flag[] = $value;
echo "Import $value successfully! <br>" ;
// $query1 =
// "Delete FROM hklcanet_pha.psr this
// WHERE year(psr.ReportDate) = $input3
// AND month(psr.ReportDate) = $input2";
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
into table hklcanet_pha.psr fields terminated by ','
optionally enclosed by '\"'
lines terminated by '\n'
ignore 1 lines
(`ReportDate`, #dummy, #dummy, `Team_refno`,`Name/Description`,`Status`,`PIC`,`RequestDate`,`TargetEndDate`,`ActualEndDate`,`PlanStartDate`,`ActualStartDate`,`PlanUATDate`,`ActualUATDate`,`PlanImplement`,`ActualImplement` )";
//echo "Import $value successfully! <br>" ;
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
if(sizeof($flag) == 0){
//Display all the file names in alert
$failedFiles = implode(",",$flag);
echo "<script>alert('Import Failed for files : ".$failedFiles."');</script>";
}
unset($value);
?>
Related
i have 2 file tst.html and tst.php
tst.html body is
<form>
<input id="search" type="text" size="30" onkeyup="showresult(this.value)" >
<div id="suggest"></div>
</form>
<script>
function showresult(val){
if(val.trim() == ""){
}else{
var xttp = new XMLHttpRequest() ;
xttp.onreadystatechange = function () {
var s = xttp.responseText ;
if(s.match("zerorow")){
document.getElementById("suggest").innerHTML = "zero" ;
}else {
try {
window.alert(s) ;
var arr = JSON.parse(s) ;
}
catch(err) {
document.getElementById("suggest").innerHTML = err.message;
}
}
};
xttp.open("POST" , "tst.php" ,true) ;
xttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded") ;
xttp.send("val="+val) ;
}
}
and tst.php
<?php
$servername = "localhost";
$dbusername = "mamad";
$dbpassword = "";
$dbname = "t1" ;
// Create connection
$conn = mysqli_connect($servername, $dbusername, $dbpassword , $dbname);
if (!$conn) {
die("Connection failedddddddddd: " . mysqli_connect_error());
}else{
$val = $_POST["val"] ;
$sql = "SELECT tag FROM tags WHERE tag LIKE '$val%'";
$result = mysqli_query($conn, $sql);
if($result){
if(mysqli_num_rows($result) > 0){
$arr = mysqli_fetch_all($result , MYSQLI_NUM) ;
echo json_encode($arr) ;
}else{
echo "zerorow" ;
}
}else{
echo die("faileddd " . mysqli_connect_error());
}
}
?>
assume in my database i have two record tag1 and tag2 in tag column
and
$arr = mysqli_fetch_all($result , MYSQLI_NUM) ;
json_encode($arr) ;
if you input t alphabet in input field tst.php
pass a 2 dimensional array as string like this [["tag1"],["tag2"]]
but
var arr = JSON.parse(s) ;
throw a syntax error with JSON.parse: unexpected end of data at line 1 column 1 of the JSON data message
and one more question i just want want column of data of table in my database is there any function that do it and give one dimensional array ?
sorry if it become long question .
The onreadystatechange event fires on every state change, not only if the request is finished and the result is returned.
You have to add some checks to make it work:
The readyState must be in status DONE, and
the http status must be 200
In code that looks like this:
xttp.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xttp.status === 200) {
var s = xttp.responseText ;
if(s.match("zerorow")){
document.getElementById("suggest").innerHTML = "zero" ;
} else {
try {
window.alert(s) ;
var arr = JSON.parse(s) ;
} catch(err) {
document.getElementById("suggest").innerHTML = err.message;
}
}
}
};
Hint: Better use only one return type. In your case JSON. In your code your mixing up different content types. That's bad style
Furthermore your sql is attackable with sql injections. This is an security and safty issue
I am getting search results from a MySQL table from a string entered in an input text from a HTML page.
Using AJAX, when the user selects one of the result rows the browser is redirected to a PHP file.
What I need is to put the result on another TextField from the same page and not to open another page.
Here is the code that I have now:
PHP part that is sending the needed output results:
/************************************************
Search Functionality
************************************************/
// Define Output HTML Formating
$html = '';
$html .= '<li class="result" >';
$html .= '<img src="iconos_especialidades/logo" width="94" height="94" />';
$html .= '<a target="_blank" href="urlString" >';
$html .= ' '.'<h3>nameString</h3>';
$html .= '</a>';
$html .= '</li>';
// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = 'SELECT * FROM tb_especialidades WHERE especialidad LIKE "%'.$search_string.'%" OR especialidad LIKE "%'.$search_string.'%" ORDER BY especialidad';
// Do Search
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['especialidad']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['especialidad']);
$display_url = 'opinar_doc_loc.php?id='.$result['id_especialidad'];
if ($result['icono'] == ""){
$display_logo = "nada.jpg";
}
else {
$display_logo = $result['icono'] ;
}
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Insert LOGO
$output = str_replace('logo', $display_logo, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No se ha encontrado la especialidad buscada.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Insert LOGO
$display_logo = "nada.jpg";
$output = str_replace('logo', $display_logo, $output);
// Output
echo($output);
}
}
And here is the JQuery/Ajax Part:
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "php/search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
How could I put the needed value from the database $result['id_especialidad'] on a TextField from the HTML page?
You can achieve this by returning a json object with more than one key. For example from php:
<?php
$result = array('id' => $result['id_especialidad'], 'data' => $output);
echo json_encode($result);
?>
Then from JS you can decode and handle as two separate pieces of data:
$.ajax({
type: "POST",
url: "php/search.php",
data: { query: query_value },
cache: false,
success: function(html){
var response = $.parseJSON(html);
$("#my_input_field").val(response.id);
$("ul#results").html(response.data);
}
});
EDIT -------
I've added the correct id field from the query result (see above again), you will also need to edit the output from the no results part of the php file (after the 'else') to echo the json encoded array... for example:
<?php
$result = array('id' => 0, 'data' => $output);
echo json_encode($result);
?>
You question is a little bit confusing...
After click in the result list (LIs), you want to put the redirect page to a text field instead of open a new page ?
If yes, you need to do another ajax to get the page content and them put the content in the text field.
I have a dynamic search which uses jQuery and a PHP search file to dynamically show the results below. I just changed my log in scripts and sessions; now i am having issues with a search bar that searches through the members in a DB. When I was going through the testing I see that on each keyUp the jQuery function runs properly but there is some sort of issue inside of my search.php file. It seems like there is no $userCount or $userCount = 0 because it will display "There Were No Search Results"which only happens when it equals $userCount== 0
Here are the parts of my index.php
<script type="text/javascript">
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt == '') {
// $.post("includes/search.php", {searchVal:searchTxt},
// function(output){
// $("#userResults").html(output);
// });
}else{
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
console.log(output);
}
}
</script>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Or Last Name | Press Space To View All Employees" onkeyup="searchUserQ();" />
<submit type="submit" />
div id="userResults">
</div>
</form>
and here is my search.php file
<?php
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%' or
lastName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$passwordQ = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$passwordQ' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Any suggestions why this is happening?
The reason for the error in the title is that you have console.log(output) outside the callback function. This has two problems: First, the variable output is not in scope; second, it runs immediately, not after the AJAX call returns. Move it into the callback:
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
console.log(output);
$("#userResults").html(output);
});
}
}
I have been trying to pass my phantomjs console output back to the php file that executed it, but I only get and empty array with this code. It also happens immediately, which makes me think its attempting to get the return before the phantomjs script has even run.
<?php
$user= 'dafjdh#kjsdf.com';
$pass='dumfmh';
$response = exec("/home/jef28/public_html/swipr/phantomjs /home/jef28/public_html/swipr/login.js $user $pass", $output);
echo $output;
?>
The last lines of my .js file are
console.log(document.querySelectorAll('html')[0].outerHTML);
return document.querySelectorAll('html')[0].outerHTML;
How can I pass the console output back to php?
I use this function and it works just fine .
function execute($script, $args = array(), $options = array(), $bin = 'F:/----/phantomjs-1.9.8-windows/phantomjs.exe', $debug = true) {
$option_str = '';
foreach ($options as $option => $value)
{
$option_str .= '--'.$option.'='.$value.' ';
}
// Escape
$cmd = escapeshellcmd("{$bin} {$option_str}{$script} " . implode(' ', $args));
if($debug) $cmd .= ' 2>&1';
// Execute
$result = shell_exec($cmd);
if($debug) return $result;
if($result === null) return false;
// Return
if(substr($result, 0, 1) !== '{') return $result; // not JSON
$json = json_decode($result, $as_array = true);
if($json === null) return false;
return $json;
}
I am trying to pass user's info from mysql to the webpage, if the user has logged in but can't get it to work. If I put a wrong email or password it will show the error message but if the credentials are ok it would do anything...
on php file:
$sql = "SELECT * FROM users WHERE email='$l_email' AND password='$l_password'";
$query = mysql_query($sql) or die ('Error: ' . mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1)
{
echo "You have entered a wrong email or password!";
}
else {
$memberInfo = array();
while( $row = mysql_fetch_array( $query ) )
{
$memberInfo[] = $row;
}
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
}
on js file:
$.post("./includes/checkOut.php",{ l_email1: l_email, l_password1: l_password },
function(data) {
if(data=='1')
$("#checkOut_form")[0].reset();
$("#login_returnmessage").html("");
$("#memberInfo").hide("");
var memberInfo = jQuery.parseJSON(memberInfo);
for( var i in memberInfo )
{
var f_name = memberInfo[i].f_name;
var l_name = memberInfo[i].l_name;
var phone = memberInfo[i].phone;
}
$("#loggedinInfo").show("");
$('#_f_name').val(f_name);
$('#_l_name').val(l_name);
$('#_email').val(l_email);
$('#_phone').val(phone);
}
$("#login_returnmessage").html(data);
});
If you use return outside a function then it terminates the script at that point. This is exactly what you're doing here:
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
You need to remove the return statement.
You should also add a Content-type: header to the response to tell the browser to expect JSON:
header('Content-type:application/json');
echo json_encode( $memberInfo );
Your Javascript code is checking the response for the value 1, which you're not sending, so the code that updates the display won't execute.
Lastly:
don't store passwords unencrypted - use password_hash()
don't use mysql as it's deprecated - use mysqli or PDO
ensure you escape your inputs before passing them to the database (or better, use prepared statements (not supported by mysql_*()).