concat two columns - php

how do I concat two columns? I need it to have FIRSTNAME AND LASTNAME to equal $Employee_Name I tried different combinations and still doesn't work. Also I know this has a huge SQL injection issue. I do not know yet how to correct the issue I am looking it up.
<?php
header('Content-Type: application/json');$db_conx = mysqli_connect("localhost", "root", "systems399","employees_db");
$Employee_Name= $_POST["Employee_Name"];
$sql="SELECT * FROM names WHERE FIRSTNAME='$Employee_Name' ";
$query= mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$rc= $row["EMPLOYEE_NUMBER"];
echo json_encode ($rc);
?>
I tried it this way and it doesn't work.
<?php
header('Content-Type: application/json');
$db_conx = mysqli_connect("localhost", "root", "systems399", "employees_db");
$Employee_Name= $_POST["Employee_Name"];
$sql="SELECT * FROM names WHERE FIRSTNAME='$Employee_Name' AND LASTNAME='$Employee_Name'";
$query= mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$rc= $row["EMPLOYEE_NUMBER"];
echo json_encode ($rc);
?>
Here is my Javascript code
$(document).ready(function() {
$("#Employee_Name").change(function() {
var Employee_Name = $(this).val();
if (Employee_Name != '') {
$.ajax({
type: "post",
url: "insert.php",
data: "Employee_Name=" + Employee_Name,
datatype: "json",
success: function(data) {
$("#Employee_Number").val(data);
$('#Employee_Number').css("background-color", "#B3CBD6")
$('#Employee_Number').animate({
backgroundColor: "#ffffff"
});
},
error: function(response) {
alert("error scripting")
}
});
} else {
$("#Employee_Number").val("");
}
});
});

There are 2 posibilities:
1.
$sql = "SELECT CONCAT(`FIRSTNAME`, ' ', `LASTNAME`) AS `EmployeeName`, * FROM `names` HAVING `EmployeeName` = '".$Employee_name."'";
2.
$sql = "SELECT * FROM `names` WHERE CONCAT(`FIRSTNAME`, ' ', `LASTNAME`) = '".$Employee_name."'";

Here is an example -
$sql = "SELECT CONCAT(`FIRSTNAME`, ' ', `LASTNAME`) AS `EmployeeName`, * FROM `names` WHERE `FIRSTNAME` = '" . $First_Name . "' AND `LASTNAME` = '" . $Last_Name' . "' ";

Related

Typeahead suggestion: get id instead of value and pass the id with the URL

I have a PHP and Javascript code that I am using for my typeahead search feature and it is working fine. But if you look at the code below, I am passing the search value, how can I grab the id and pass to the form URL?
HTML
<form method="get" class="form-inline customers" autocomplete="off" action="/customers/<?php echo id; ?> ">
<input class="customers" id="customers" type="text" name="customers">
<button type="submit" title="Search Customers"></button>
</form>
Javascript
<script>
$( document ).ready(function() {
$('input.customers').typeahead({
source: function (query, process) {
var countrycode = '<?php echo $agencyid; ?>';
return $.get('fetch_customers.php', { query: query, cc: countrycode }, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
});
});
</script>
PHP
$countrycode1 = $_GET['cc'];
$sql="SELECT
first_name,
last_name,
id,
status,
agency_id
FROM customers
WHERE (agency_id = '$countrycode1') AND first_name LIKE '%".$_GET['query']."%' LIMIT 20";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$json = array();
while( $rowscity = mysqli_fetch_assoc($resultset) ) {
$json[] = $rowscity["first_name"];
$json[] = $rowscity["id"];
}
$output = json_encode($json);
echo $output;
mysqli_close($conn);
?>
Your PHP Script:
<?php
$countrycode1 = $_GET['cc'];
$sql = "SELECT
first_name,
last_name,
id,
status,
agency_id
FROM customers
WHERE (agency_id = '" . $countrycode1 . "') AND first_name LIKE '%" . $_GET['query'] . "%' LIMIT 1";
$resultset = mysqli_query($conn, $sql) or die("database error:" . mysqli_error($conn));
$json = array();
while ($rowscity = mysqli_fetch_assoc($resultset)) {
echo $rowscity["id"]; exit;
}
?>
Your Script can be like:
<script>
$(document).ready(function () {
$('input.customers').typeahead({
source: function (query, process) {
var countrycode = '<?php echo $agencyid; ?>';
$.get('fetch_customers.php', {query: query, cc: countrycode}, function (data) {
$('form').attr('action', '/customers/' + data);
});
},
});
});
</script>

Image change from dropdown using AJAX

Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data:'id='+val,
success: function(data){
$("#style_code").html(data);
}
});
}
</script>
Here is check.php
<?php
$con=mysqli_connect("localhost","root","","db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con,$query);
while ( ($row=mysqli_fetch_array($results))){?>
<option value="<?php echo $row["color_name"]; ?>">
<?php echo $row['size'] ; ?>
</option>
<?php
}
}
?>
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.
It would be something like that :
check.php
<?php
$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
$data = new stdClass(); // This object will carry the results
while (($row = mysqli_fetch_object($results))) {
$data->option[] = $row;
}
// Another query to get the image name
$query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
if ($row = mysqli_fetch_object($results)) {
$data->image_name = $row->name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
HTML & Javascript:
...
<div class="thumb-image" id="style_image" >
<img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>
...
<script language="javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data: {id: val},
dataType:'json',
success: function(data) {
$("#style_code").children().remove(); // empty the dropdown
// Add new options in the dropdown from the result data
data.option.forEach(function (item) {
$("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
});
// Change the 'src' attribute of the <img>
$("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
}
});
}
</script>

post values with ajax, php put it in database

I want to accept user data from a form, use AJAX to post the values to a PHP script, which will insert them into the database.
JQuery:
$(".add").click(function(){
var order = {
Name: $name.val(),
Drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/ajax/api/orders.php',
data: order,
success: function(newOrder){
$orders.append('<li>Name: ' + newOrder.Name +', Drink: '+ newOrder.Drink +'</li>')
}
})
});
Php:
//open connection to mysql db
$connection = mysqli_connect("localhost","root","xxxxxxxxx","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from orders";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
can somebody help me with it?
i think you should insert before you get all orders
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
mysqli_query($connection, $sql) or
die("Error in Inserting" . mysqli_error($connection))
$id = mysqli_insert_id ($connection);
$sql = "select * from orders where Id = $id";
$result = mysqli_query($connection, $sql) or
die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
The javascript will be right this:
$(".add").click(function(){
var order = {
Name: $name.val(),
Drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/ajax/api/orders.php',
data: order,
success: function(newOrder) {
$.each(newOrder, function(order) {
//$order is a ul that have id = orders
$orders.append('<li>Name: ' + order.Name +', Drink: '+ order.Drink +'</li>');
});
}
});
});
and if you need anything ask :]
UPDATE
please update the success function you have to this
success: function(data) {
data.forEach(function(order) {
//$orders is a ul that have id = orders
$orders.append('<li>Name: ' + order.Name +', Drink: '+ order.Drink +'</li>');
});
}
UPDATE 2
success: function(data) {
var obj = JSON.parse(data);
var length = obj.length;
for (var i = 0; i < length; i++) {
$orders.append('<li>Name: ' + obj[i].Name +', Drink: '+ obj[i].Drink +'</li>');
}
}
UPDATE 3
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
mysqli_query($connection, $sql2) or
die("Error in Inserting" . mysqli_error($connection))
$id = mysqli_insert_id($connection);
$sql = "select * from orders where Id = $id";
$result = mysqli_query($connection, $sql) or
die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);

Conditional mysqli date range check to print a price in sql

This time I'm trying to make some php code to work with mysqli in order to check if today date is between a range of dates in a Mysql table, if the condition is true I need to print a price from a table otherwise it shuould print a different price from another table. so I already have all sql connections set in another php file, the problem is that when I try the code, it just shows nothing, a blank page only. This is the code im using:
<?php
$currentdate = date("Y/m/d");
//basic include files
require_once('/home/user/public_html/folder/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND $currentdate >= 'seasonal_from' AND $currentdate <= 'seasonal_to';");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice ){
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)){
echo "$ {$standard['room_price']} ";
}
} else {
if(! $seasonalpricedate ){
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalpricedate, MYSQL_ASSOC)){
echo "$ {$standard2['seasonal_price']} ";
}
}
}
?>
I already tried both codes with standardprice and seasonalprice working without a conditional, but when I try to do it like this, it does not show anything.
PostData: Im still trying to learn english, so please appologize me if I fail some words, thanks in Advance.
UPDATE: Ok so in this way it works if there is no values true its ok, it shows the standardprice, but if match the date, dont show anything, here is the code changed:
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND '$currentdate' >= seasonal_from AND '$currentdate' <= seasonal_to");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$seasonalprice = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'");
if(! $seasonalprice )
{
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalprice, MYSQL_ASSOC))
{
echo "$ {$standard2['seasonal_price']} ";
}
}
} else {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice )
{
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC))
{
echo "$ {$standard['room_price']} ";
}
}
mysqli_close($conn);
?>
So close to make it work, thanks to
UPDATE: Because you are also updated your OP, now i found what causes the problem. Ther proble were when you says: die('Could not get data: ' . mysqli_error()); And after that you want to try a while loop. while won't executed, because you terminated the script with a die(); Move the while to the else case of your if condition. See my comments.
Use this:
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
//Also display your errors.
display_errors(true);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
//Put your query into a variable, so you can dump / print it.
$sql = "SELECT `seasonal_price`"
. " FROM `hotel_seasonal_price`"
. " WHERE room_type_id = '1'"
. " AND '" . $currentdate . "' >= seasonal_from"
. " AND '" . $currentdate . "' <= 'seasonal_to'";
echo $sql;
//Try to run it in the sql directly. Is it gives back you any result?
//Do not need to
$result = mysqli_query($conn, $sql) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
//Check if we have result by echoing some dummy text
echo "Yes, we have result!";
$sql = "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'";
//Do the same as the previous query. Does it gives you back anything?
$seasonalprice = mysqli_query($conn, $sql);
if (!$seasonalprice) {
//I do not really get what happens here. If you have no seasonalprice,
//then you can not fetch_array on that!
//Move this whole section.... You've say die, and after that do a while?
die('Could not get data: ' . mysqli_error());
} else {
while ($standard2 = mysqli_fetch_assoc($seasonalprice)) {
echo "$ " . $standard2['seasonal_price'] . " ";
}
}
} else {
//Same as previous
$sql = "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'";
$standardprice = mysqli_query($conn, $sql);
if (!$standardprice) {
die('Could not get data: ' . mysqli_error());
//same here, move the while to the else...
} else {
while ($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)) {
echo "$ {$standard['room_price']} ";
}
}
}
mysqli_close($conn);

using only one query to update columns in the database - inplace edit

id car make sales
1 panamera porsche 100
2 italia ferrari 200
3 volante astonmartin 300
4 avantador lamborghini 400
5 slk mercedes 500
So guys, i have this simple table in my database. And i'm gonna echo this table in a while loop.
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" data-id="'.$row['id'].'" data-col="car">'.$row['car'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="make">'.$row['make'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="sales">'.$row['sales'].'</li>';
}
?>
</ul>
The idea is to update this table using jQuery in-place editor. So here is the code-
$(document).ready(function()
{
$(".editable").bind("dblclick", replaceHTML);
$(".editable2").bind("dblclick", replaceHTML2);
$(".btnSave, .btnDiscard").live("click", handler);
function handler()
{
if ($(this).hasClass("btnSave"))
{
var str = $(this).siblings("form").serialize();
$.ajax({
type: "POST",
async: false,
url: "handler.php",
data: str,
});
}
}
function replaceHTML()
{
var rowId = $(this).parent('li').data('id');
var colName = $(this).parent('li').data('col');
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"" + colName + "\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + rowId + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
}
);
This is an in-place edit code i got it from the internet and i just tore it down to basic level just to understand the codes. Behrang Saeedzadeh helped me improvise "replace HTML" function.
And here is the update query in handler.php file -
<?php
require("db.php");
if (isset($_POST['id']) && isset($_POST['car'])) {
$id = mysql_real_escape_string($_POST['id']);
$car = mysql_real_escape_string($_POST['car']);
$query = "UPDATE inplace SET car ='$car' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['make'])) {
$id = mysql_real_escape_string($_POST['id']);
$make = mysql_real_escape_string($_POST['make']);
$query = "UPDATE inplace SET make ='$make' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['sales'])) {
$id = mysql_real_escape_string($_POST['id']);
$sales = mysql_real_escape_string($_POST['sales']);
$query = "UPDATE inplace SET sales ='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
?>
Here in the update query, i have to write a different query for each column. The question is how do i update using only one query for all the columns?
if(isset($_POST['id']) {
$id = mysql_real_escape_string($_POST['id']);
$arr_check = array("car", "make", "sales");
$result = array();
foreach($arr_check as $check) {
if(isset($_POST[$check]))
$result[] = $check . '="' . mysql_real_escape_string($_POST[$check]) . '"';
}
$result = implode(", ", result);
if($result != '') {
$query = "UPDATE inplace SET {$result} WHERE id='{$id}'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;
}
}
that should more or less do it
First of all, you might be better off making the entire list a form to begin with, and storing the existing records in hidden form fields. Then, you should have the handler.php script check if any new form entries were submitted, and store them into variables. If no new entry was made, the variables will contain the default value.
Then, you can submit the whole update query in one shot:
$query = "UPDATE inplace SET car ='$car', make='$make', sales='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;

Categories