I am making a private message system and i created a php search page, I am using JQuery to pass a variable from a text field on keyUp to a PHP file called USearch.php or Username Search. Here is my code:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'] = $User;
}
}
}
echo json_encode($USearch);
?>
As you can see, my code has no errors, my problem is that i am searching Users in a DB which means i am searching 1 word or string, by using this PHP code, i would have to type in the exact username for the function to return a value. My real intention was to search the string and return all similar usernames according to my input string.
Like Jon said - you want to use % where you want your SQL to have a wild card.
If you want all values where name is like matt you would do
WHERE name LIKE '%matt%'
Related
I have the below PHP code which picks up the posted form data from another file, executes SELECT queries to find all related data form the various tables (SalesDB, CustDB and ProdDB), and then executes an INSERT INTO query to add a row into the 'SalesDB' table. The form has dynamically added rows, which gives each newly added row a unique ID, for example:
...<input type="text" id="prodName_1" name="prodName[]" value="">
...<input type="text" id="prodName_2" name="prodName[]" value="">
.
.
...<input type="text" id="prodName_Z" name="prodName[]" value="">
However, when the PHP script runs for e.g. 3 rows of product lines, it only executes the $queryinsert query for the first iteration and inserts the first product line of the form. Why won't it loop through the array? See the php script below:
<?php
$db = new SQLite3('../xxx.db');
if(!$db){
echo $db->lastErrorMsg();
exit;
}
if (empty($_POST['custID'])) {
$errorMSG = array("No customer selected");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
} else {
$custID = $_POST['custID'];
$queryInsert = $db->prepare("INSERT INTO 'SalesDB'
(SalesID,CustID,ProdID,ProdQty,ProdPrice,ProdCurr,ProdVAT,SalesPrice,SalesVAT,SalesSum)
VALUES (?,?,?,?,?,?,?,?,?,?)");
$queryInsert->bindParam(1,$salesID);
$queryInsert->bindParam(2,$custID);
$queryInsert->bindParam(3,$prodID);
$queryInsert->bindParam(4,$prodQty);
$queryInsert->bindParam(5,$prodPrice);
$queryInsert->bindParam(6,$prodCurr);
$queryInsert->bindParam(7,$prodVAT);
$queryInsert->bindParam(8,$salesPrice);
$queryInsert->bindParam(9,$salesVAT);
$queryInsert->bindParam(10,$salesSum);
$querySalesID = "SELECT MAX(SalesID) AS max_SalesID FROM 'SalesDB'";
$resultSalesID = $db->query($querySalesID);
while ($row = $resultSalesID->fetchArray()) {
$salesID = $row['max_SalesID'] + 1;
}
foreach($_POST['prodName'] as $prodName => $value) {
if (!$value) {
$errorMSG = array("Empty product fields");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
} elseif ($value == "Product not found") {
$errorMSG = array("Invalid products in order form");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
}
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
$resultProd = $db->query($queryProd);
while ($row = $resultProd->fetchArray()) {
$prodID = $row['ProdID'];
$prodPrice = $row['ProdPrice'];
$prodQty = $row['ProdQty'];
$prodVAT = $row['ProdVAT'];
$prodCurr = $row['ProdCurr'];
$salesPrice = $prodQty * $prodPrice;
$salesVAT = number_format($prodQty * $prodPrice * $prodVAT,2);
$salesSum = $salesPrice + $salesVAT;
}
$result = $queryInsert->execute();
}
}
?>
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
There are some issues in the script:
1) Instead of doing exit inside the foreach, do continue to skip the single actual iteration.
As in the official documentation:
continue is used within looping structures to skip the rest of the
current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration.
Try this code:
foreach($_POST['prodName'] as $prodName => $value) {
if (!$value) {
$errorMSG = array("Empty product fields");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
continue;
} elseif ($value == "Product not found") {
$errorMSG = array("Invalid products in order form");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
continue;
}
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
$resultProd = $db->query($queryProd);
while ($row = $resultProd->fetchArray()) {
$prodID = $row['ProdID'];
$prodPrice = $row['ProdPrice'];
$prodQty = $row['ProdQty'];
$prodVAT = $row['ProdVAT'];
$prodCurr = $row['ProdCurr'];
$salesPrice = $prodQty * $prodPrice;
$salesVAT = number_format($prodQty * $prodPrice * $prodVAT,2);
$salesSum = $salesPrice + $salesVAT;
}
$result = $queryInsert->execute();
}
2) your query are using user inputs without check their contents, so your script maybe open to SQLInjection!
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
3) if the query does return nothing, the script does not enter in the while loop, so it seems that the foreach do only one iteration but instead it do all iterations without enter in the while because of empty result from that query.
I suggest to you to debug all pieces of your code by printing out variables content using var_dump, e.g.:
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
I would like to ask, what will be the best way to code using SQL and PHP, on how to check if the input in a textfield matches with a value in an SQL column?
I only have three values in the table. my targets are:
retrieve (POST) the value of the input
check the whole column to see if any matches the "promo code" typed
the "tinyint" used value will turn to 1
echo or affect other database tables if conditions are met
pseudocode will be alright, I would just like the proper procedure.
UPDATE: I tried the solution from #Bitwise Creative, im not getting an echo to appear, which part did i do wrong? also, i got my db where the table is located using a variable.
<form method="get">
<input type="text" name="lux_code" placeholder="ENTER PROMO CODE" style="text-align:center;">
<input type="submit" class="full_width btn color-white mwc-orange-background-color" name="redeem" value="REDEEM">
</form>
<?php
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
if (isset($_POST['redeem']) && $_POST['redeem'] == 'REDEEM'){
if (isset($_POST['lux_code']) && $_POST['lux_code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM promocode_3 WHERE coupon_code = ? AND used = ?', array($_POST['lux_code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE promocode_3 SET used = ? WHERE coupon_code = ?', array(1, $_POST['lux_code']));
// Additional handling...
echo 'Code accepted!';
}
}
}
?>
Assuming coupon_code has a unique index... Something like:
<?php
if (isset($_POST['code']) && $_POST['code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM coupons WHERE coupon_code = ? AND used = ?', array($_POST['code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE coupons SET used = ? WHERE coupon_code = ?', array(1, $_POST['code']));
// Additional handling...
echo 'Code accepted!';
}
}
You can do like this-
$couponcode = $_POST['coupon'];
$sql = "update table_name set used = 1 where coupon_code = $couponcode && used = 0";
The best way is to retrieve all your unused coupon codes and then iterate over the collection and check if the posted value is a match.
I would write a function in my functions.php file as so:
function getCoupons() {
global $db;
try {
$stmt = $db->prepare("SELECT * FROM coupons WHERE `used` = 0");
$stmt->execute();
return $stmt->fetchall();
} catch (Exception $e) {
echo $e->getMessage();
}
}
I would then call the function and store the results into an array in my test.php file like so:
$coupons = getCoupons();
I would also need the posted value, I'll retrieve it like so:
$couponCode = $_POST['coupon'];
I would then iterate over the result set to check for a match in the same file:
$match = false;
foreach($coupons as $coupon){
if($coupon['coupon_code'] == $couponCode){ //check to see if posted value matches
$match = true;
$stmt2 = $db->prepare("UPDATE coupons SET used =
'1' WHERE p3id = :id");
$stmt2->execute(array(
':id'=>$coupon['id']
));
break;
}
}
if($match){
echo 'Coupon code exists!';
} else {
echo 'No Coupon code exists!';
}
I have added my code below, i am new to php and mysql and trying to search mysql using php based on user inputs and working really fine. But not sure how to highlight the user input value while displaying from mysql.
$output = NULL;
if(isset($_POST['submit'])){
$mysqli = new mysqli("localhost","root","","test");
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM books WHERE BookContent LIKE '%$search%'");
if($resultSet->num_rows>0){
while($rows = $resultSet->fetch_assoc()){
$BookContent = $rows['BookContent'];
//$output = preg_replace("/($search)/i",'<span class="highlight">$1</span>', $output);
echo $output = "" ."Your search results--> $BookContent"."<br>";
}
}else{
echo $output = "No result" ;
}
}
?>
just add this in your page.
CSS:
.highlight{background-color:yellow}
jQuery:
$("body").highlight("<?php echo $search; ?>");
I need a little help of my brilliant friends.
Actually i m new to development so that i have no much idea how can i show my page in words like www.testsite.com/index.php?pname=**Home** except of www.testsite.com/index.php?pid=**1**
i have the following code for showing page in number
if (!$_GET['pid']) {
$pid = '1';
} else {
$pid = ereg_replace("[^0-9]", "", $_GET['pid']); }
and the sql code
$sqlCommand = "SELECT id, link FROM main_page WHERE showing='1' ORDER BY id ASC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$menu='';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$link = $row["link"];
if ($linklabel){
$menu .=''. $link .'';
}}
i want to show and href name of page not id how can i do that.
help plz
Your example will fail if I enter *1*2*3*
you should be searching for the contents of
**(contents)**
and nothing else.
That will get you the name and the number.
Here is my example
$string = "**123naasdme456**";
preg_match("/[^\*+](?P<val>\w+)[^\*+]/",$string,$matches);
echo $matches[0];
will echo 123naasdme456
and here it is implemented into your code
function getReal($urlVar)
{
if(preg_match("/[^\*+](?P<val>\w+)[^\*+]/",$urlVar,$matches))
{
return $matches[0];
}
return false; // or default value
}
$pid = getReal($_GET['pid']);
$name = getReal($_GET['pname']);
You should add an extra field in your database (table main_page) with the name name or something similar. Then you could:
if (!$_GET['pname']) {
$pid = 'home';
} else {
$pid = mysql_real_escape_string($pid);
$sql = mysql_query("SELECT name FROM main_page WHERE name = '$pid'");
if (mysql_num_rows($sql) == 1))
{
echo "Content";
} else {
echo "404 error. Couldn't find the page you were looking for.";
}
}
URL Rewriting. http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/
I have a signup page on my website where a user must provide a email address and password only.
I want to be able to create a username for this user automatically by using the first part of the email provided;
User supplies gordon#yourdomain.com, i want to make username 'gordon'
I don't need explanation on how to create form or submission of data to database, just the code to extract data from email provided, and if necessary, if duplicate occurs add number to end.
Hope this makes sense, seems like a basic function but couldn't find examples of it anywhere on net!
This is not a good idea, just use their full email address. The following email addresses could be different people, but they will become the same under your system.
samename#gmail.com
samename#yahoo.com
Adding a number to the end will make the user remember something unique to your system and cause much confusion on their end.
Agreed, you're stripping a necessarily unique ID into a non-unique ID. Unless you want to add some sort of handling to add a number to the username or something. If that's what you really want to do, this should set $username to the stuff before the email address:
<?php
$username = preg_replace('/([^#]*).*/', '$1', $email);
?>
Something like:
$username = left($email, stripos($email, '#'));
should do. You may want to learn regular expressions for these kinds of task.
Then you add the counter:
function countOccurrences($name)
{
$con = mysql_connect(___, ___, ___);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(___, $con);
$result = mysql_query("
SELECT COUNT(*) AS countOccurrences
FROM users
WHERE username LIKE '" . mysql_real_escape_string($name, $con) . "%'
");
$row = mysql_fetch_array($result);
$number = $row['countOccurrences'];
mysql_close($con);
return $number;
}
and then:
$countUsers = countOccurrences($username);
if ($countUsers>0)
{
$username = $username . $countUsers;
}
IMPORTANT: Consider using the whole email as username: you don't want gordon#flash.net to be considered equal to gordon#clash.com
NOTE: example code counts gordon, gordon1, gordon2 but gordonbah, gordonq, gordonxxx too
NOTE: this is pretty rough, and should not be considered best PHP practice; it's just to give the general idea
$username = gordon#example.com;
$username_arr = explode('#',$username);
$username = $username_arr[0];
if( !is_taken( $username ) )
{
//The name is not taken.
}
else
{
//The name is taken, add numbers and do the search again.
}
function is_taken( $username )
{
$db_link = mysql_connect($host,$user,$pass) or die('Could not connect to database');
$username = mysql_real_escape_string( $username );
$sql = "SELECT * FROM `database`.`users` WHERE `username` = '$username'";
$res = mysql_query( $sql , $db_link );
return mysql_num_rows( $res ) == 1;
}
<?php
preg_match('/[^#]+)#/',$email,$matches);
$username = $matches[1];
check_availability($username);
?>
Should suit your needs :D
$username = substr($username, 0, strpos($username, '#'));
$username = mysql_real_escape_string($username);
$result = mysql_query('SELECT `username` FROM `users` WHERE `username` = \'' . $username . '%\';');
if (mysql_num_rows($result) > 0) {
$i = 0;
while ($name_arr = mysql_fetch_assoc($result)) {
$name = $name_arr['username'];
$after = substr($name, strlen($username));
if (ctype_digit($after)) {
if (($after = (int) $after) > $i) {
$i = $after;
}
}
}
if ($i > 0) {
$username .= $i;
}
}
As of PHP 5.3.0 you can also use:
$email = 'test#stackoverflow.com';
$user = strstr($email, '#', true);
This will return all the string from the beginning to the first occurrence of '#'. Which in this case is:
test
I use something like this,
$cust_email = "test#gmail.com";
$parts = explode("#", $cust_email);
$cust_name = $parts[0];
I use to set default User Name if user do not set his / her name in the profile.
You can use strstr function to find specific word from string
<?php
$username = strstr("username#domain.com",'#',true); //get text before #
/*
echo strstr("username#domain.com","#"); // get text after #
*/
check_availability($username);
?>