PHP and MySQLi query always returning 0 - php

The following code seems to be not working correctly. I'm new to PHP and jQuery.
php:
<?php
//if (!defined('BOOTSTRAP')) { die('Access denied'); }
//if we got something through $_POST
if (isset($_POST['postcode_locator_search'])) {
// here you would normally include some database connection
//include('config.local.php');
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','test','c#W)ukmd[0bm','test');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
// never trust what user wrote! We must ALWAYS sanitize user input
$postcode_q = mysqli_real_escape_string($mysqli, $_POST['postcode_locator_search']);
$postcode_q = htmlentities($postcode_q);
// A select query. $result will be a `mysqli_result` object if successful
$result = mysqli_query("SELECT description FROM cscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1");
if($result === false) {
// Handle failure - log the error, notify administrator, etc.
echo '1';
} else {
// Fetch all the rows in an array
echo '0';
}
$mysqli->close();
}
?>
JS / HTML:
{assign var="prod_id" value=$product.product_id}
<form action="search_postcode.php" method="post" class="postcode_locator_form" name="postcode_locator_form">
<div class="ty-control-group">
<label for="postcode_locator_search{$block.block_id}" class="ty-control-group__title">{__("postcode_search")}</label>
<p class="filling-notice">{__("postcode_search_desc")}</p>
<div class="ty-input-append ty-m-none">
<input type="text" size="20" class="ty-input-text" id="postcode_locator_search" name="postcode_locator_search" value="{$postcode_locator_search.q}" />
{include file="buttons/go.tpl" but_name="postcode_locator.search" alt=__("search")}
</div>
</div>
</form>
<div class="filling-status filling-success">
<h3>Add filling to your bean bag</h3>
<p>Searched postcode: <span class="searched-postcode"></span></p>
<p class="beans-msg">{__("add_some_beans_success")} {__("click_here")}</p>
</div>
<div class="filling-status filling-failure">
<h3>Add filling to your bean bag</h3>
<p>Searched postcode: <span class="searched-postcode"></span></p>
<p class="beans-msg">{__("add_some_beans_error")}</p>
</div>
<script>
$(function() {
$(".filling-status").hide();
$(".postcode_locator_form .ty-btn-go").click(function() {
// getting the value that user typed
var searchString = $("#postcode_locator_search").val();
// forming the queryString
var data = 'postcode_locator_search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "search_postcode.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$(".searched-postcode").html(searchString);
},
success: function(data){ // this happens after we get results
console.log(data);
if(data == '0'){
$(".filling-status.filling-success").show();
} else if(data == '1'){
$(".filling-status.filling-failure").show();
}
}
});
}
return false;
});
});
</script>
The communication is all working, but it always returns 0 as a success from whatever I search for and seems to not check database for the result.
What I need is if I search something and it's a match, to return 0 as a success but if not found / a match to return 1 as a failure.

If you want to retrieve your data:
$result = mysqli_query("SELECT description FROMcscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1");
if($result === false) {
// Handle failure - log the error, notify administrator, etc.
echo '1';
} else {
// Fetch all the rows in an array
while($row = mysqli_fetch_assoc($result)){
echo $row['id']; //prints the resulted id
}
}

Use mysqli_num_rows to detect if you have a result
if($result === false or mysqli_num_rows($result) === 0) {
echo '1';
}
I would recommend breaking this into two if conditions though so that you handle errors separately from a query with no result

Related

Validate promo code from MySql table and mark as "used" when form is submitted

I have an HTML form starting with an input field, where the user have the option to write a promo code to get some discount ....
What I am trying to do here. I need to create a keyup functionto check if the typed code is found in the MySql Promo Codes table.
If found, write something in the placeholder ...., else, write something else ....
Also if the form is submitted in need the PHP to write 'Yes' in the code corresponding MySql Used column...
<form id="form" class="form" name="RevitForm" action="form_revit_architecture_submitted" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
<div class="field" style="background-color:#f3f3f3;">
<span id="promo-msg" style="color:#093; position:relative; bottom:3px; font-style:italic; font-size:13px">[HTML is replaced when successful.]</span>
<center><input style="font-family:Lato; text-align:center; max-width:200px;" type="text" id="PromoCode" name="PromoCode" maxlength="5" size="15px" placeholder="Promo Code"></center>
</div>
//other input fields
</form>
<!-- Promotion Code Match -->
<script>
$("#PromoCode").keyup(function() {
if ($(this).val().length == 5) {
//post the code and check the it in the MySql table thru the PHP file "request.php"
//if code found {write something in $(#promo-msg) } else {do something else}
}
});
</script>
And in the PHP in need to excute something like
<?PHP
$code = ucwords($_POST['PromoCode']);
$con=mysqli_connect("localhost","x","y","academy_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
// if $code is found and the corresponding `Used` column does not == 'Yes' return as found
//else return as not found
?>
To do that, we need 2 files.
HTML, form + jQuery AJAX keyup event and check DB
PHP connect to DB to check the promo code
1.HTML
<html>
<head>
<title>Promo check</title>
<!-- load jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 10;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' is already used correct.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<input type='text' id='code'>
<div id='Promo_code_status'></div>
</body>
</html>
2.PHP: check_code.php
You will need to use your connection data ($host, $user, $pass, $dbdb) and maybe change the table & field names.
<?php
//connect to database
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select promoCode, used from testtable where promoCode = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
Do it like this:
"SELECT * FROM Promo Codes WHERE Code LIKE '$code' AND Used='yes' "
Also,To update parameter 'used':
UPDATE Promo Codes SET used='Yes' WHERE Code= '$code'
For the keyup function, you need to learn about AJAX requests. Since it's the medium for communicating with the server through the client
jQuery AJAX: http://api.jquery.com/jquery.ajax/

Checking for existing users in DB using Ajax and PHP

I'm running into a problem where the code keeps on showing that the user name is available, even though it is existing in the DB. Can anyone solve the problem that I'm running into? Down below is my code.
PHP
// Define $username
$username=$_POST["emailAddress"];
// Create Connection
$db = new mysqli($server, $user, $password, $database);
// Check Connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
// SQL query to fetch registerd users and finds user match.
$query = "SELECT email_address FROM users WHERE email_address='$username'";
$result = mysqli_query($db,$query);
$rows = mysqli_num_rows($result);
//if number of rows fields is bigger them 0 that means it's NOT available '
if($rows>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
mysqli_close($db); // Closing Connection
jQuery
$(document).ready(function () {
//when button is clicked
$('[name="checkAvail"]').on("click", function () {
check_availability();
});
});
//function to check username availability
function check_availability() {
//get the username
var username = $('[name="emailAddress"]').val();
//use ajax to run the check
$.post("checkusers.php",
function (result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});
}
HTML
<div class="form-group">
<button class="btn btn-default" name="checkAvail">Check Availability</button>
<label for="emailAddress" class="col-sm-5 control-label">Email:</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="emailAddress" name="emailAddress" placeholder="Email" autocomplete="off">
</div>
</div>
Your ajax doesn't send any data...so $_POST["emailAddress"]; is going to be empty in your php
You need to add a data object as second argument of $.post
$.post("checkusers.php",{emailAddress : username },function (result) {
// success handing code left out for clarity
});
Also you should check that the input isn't empty before user is allowed to check it. No point in sending invalid empty values to server.
There are lots of simple javascript validation plugins you can use.
Similarly on server should be valididating the user input. This is the most important point of validation because javascript can be worked around to allow sending anything
You aren't sending any data to the Post Page.
$.post( "checkusers.php", { emailAddress: username})
.done(function( data ) {
if (data == "1") {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});
Check the jQueryDocumentation
according to your php script try this if (result==0)
function (result) {
//if the result is 0
if (result == 0) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}

ajax error handling / show error if mysql result is false?

I have a form where a user can input a voucher code:
<form>
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
the user can click on my div 'promo_check' which runs the following ajax:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
$.ajax({
type: "POST",
url: "process_promo.php",
data: {data:promo},
success: function(data)
{
window.alert(data);
}
});
});
});
</script>
this then executes my mysql query to check if the voucher exists in the database and that the $_SESSION['user_name'] / i.e. the logged in user has the permission to use that voucher.
process_promo.php:
<?php
$username = "mark";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$_SESSION['username'] = 'mark';
$promo = $_POST['data'];
$query = "SELECT * FROM hewden1.supplier_users WHERE promo_code = '$promo'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (mysql_num_rows($result) > 0) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}else{
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
} }
}else{
echo 'error';
}
}
?>
this all works fine, if the voucher code matches for that user then it echo's 'correct' and my ajax will show an alert saying 'correct'. Then if the voucher code does not match for the user then it echo's 'not correct for user'.
The problem i have is when the voucher is not valid at all and cannot be found in the database it is suppose to echo 'error' however ajax show a blank/empty alert message instead of showing 'error'.
I think this is because i am using success: in my ajax but when i try to add an error: call back my script stops working. can someone please show me what i'm doing wrong? thanks in advance
Looking at process_promo.php, if you get no result from the database query, then the contents of the while loop never get executed. Putting it another way, inside the while loop you'll never have a mysql_num_rows($result) == 0 condition.
Here I moved your while loop inside your mysql_num_rows check:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}
else {
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
}
}
}
}
else {
echo 'error';
}
...which also pulls the error report outside the while loop and gives it a chance to execute.

navigating to another view if count=1 in php file using sench

i created a sencha touch application,in my controller i used the ajax code as
if (condition is true){
Ext.Ajax.request({
url: 'http://localhost/../abc.php?action=check',
params: valuesUser,
method: 'POST',
success: function(response){
var text = response.responseText;
console.log(response.responseText);
if(response.responseText == 'exists')
{
//Ext.Msg.alert('Success', text);
Ext.getCmp('loginform').destroy();
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
}
else{
Ext.Msg.alert('Success',text);
}
}
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});
}
else{
Ext.Msg.alert('Error', 'All the fields are necessary');
}
my abc.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('RegisterForm',$con);
if($_REQUEST["action"]== "check"){
$query = "SELECT name FROM userdetails WHERE name ='" . $_POST['userName'] . "' ";
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
if($count == 1)
{
echo('values are in the db');
}
else
{
echo("values aren't in the db");
}
}
?
if contion is true in the controller code it goes to abc.php and checks name exists in the db are or n't.if name exist then it should open another view ,otherwise it should display alert msg as values aren't in the db.but by using the above code ,im navigating to another view in both cases (values are in db,values aren't in the db).can anyone help me to do this. thanks in advance...
You need to put condition in your sencha code based on the returned value from PHP. Something like:
if(response.responseText == 'exists')
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
else
Ext.Msg.alert('Success', text);
Moreover do
echo 'exists';
instead of
echo('values are in the db');

PDO: Im trying to display multiple rows from while loop using json_encode

here is my problem... i am trying to return multiple rows without refreshing the page from my a PDO statement using the 'LIKE' CLAUSE, the problem is it only returns one row and not the rest...can somebody please help me? thanks in advance
Here is my html form:
<h2>Please insert the username you would like to search for</h2>
<div align="center" id="loader_div"><span id="search_result"></span></div>
<form action="send/search.php" method="post" id="search_form">
<input type="text" id="search_username" name="get_name" />
<input type="submit" name="submitsearch" />
</form>
<div id="get_users">
</div>
My PHP is as follows:
$search = $_POST['get_name'];
$query = $db->prepare("SELECT *
FROM `users`
WHERE `users`.`username` LIKE ? LIMIT 10");
$query->bindValue(1, "%".$search."%", PDO::PARAM_STR);
try {
$query->execute();
$data['success'] = true;
while($row = $query->fetch(PDO::FETCH_OBJ)) {
$data['users'] = " ".$row->username." ";
echo json_encode($data);
exit();
}
} catch (PDOException $e) {
die($e->getMessage());
exit();
}
And here is my jQuery to return the PHP results:
$.ajax ({
type: "POST",
url: "send/search.php",
data: $('#search_form').serialize(),
dataType: "json",
success: function(data){
if(data.success === true)
{
$("#display_users").html(data.users);
},
error: function(xhr, status, et) {
}
});
The json_encode and exit should be outside the while loop:
while($row = $query->fetch(PDO::FETCH_OBJ)) {
$data['users'] .= " ".$row->username." ";
}
echo json_encode($data);
exit();
Denpending on what format you need on the client side you decide on what to do with the $data['users'], this is also a option:
$data['users'][] = " ".$row->username." ";

Categories