Search with * for redefine part of string [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My question: I have a php search form in which I need the user to be able to redefine the search for only a part of the string.
Example (so far the user enter):
// Search Option
name: 20081111-1 //which means that the date of the item is 2008-11-11
Now, I would like the user to make a search which it will only include all the items in 2008 (desired user search):
// Search Option
name: 2008*
How can I make this option in my search? Then I can search in my database for this part of the string only.
Thanks!

Javascript:
var str = '200811111-1';
var hasSubString = str.indexOf('2008') > -1;
var startsWithString = str.indexOf('2008') == 0;
MySql:
Has Substring 2008:
select * from table where col like '%2008%'
Starts with 2008:
select * from table where col like '2008%'

Option 1:
You would take the PHP variable and replace the asterisk (*) with a percentage sign (%):
<?php
$name = $_POST['name']; // remember to sanitize it
$name = str_replace('*', '%', $name);
?>
You would then create a MySQL query using your variable:
$query = "SELECT * FROM table WHERE column LIKE '$name'";
Option 2:
Use a MySQL date query:
$query = "SELECT * FROM table WHERE YEAR(column) = '2008'";
Note that column should be a date or a datetime type.
You should add contextual help for users or even dropdowns with possible options, so they don't search for '20081', for example.

In this specific case you can use in your query
date like '%2008-%'
instead of
date = '2008-11-11'
that means search for rows where date field contains the following pattern "2008-".

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
With this in sql you search using a pattern in your case 2008, you can use regular expression for do dynamically searching only numbers that start by 2.

Related

Javascript Convert 'List()' to list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I received data from another API. But I don't know how to convert and use data.
data example
{
...
answer:'List(value1,value2,value3,value4)',
...
}
I want to iterate all answer nodes. please help.
Approach
You could capture the group between List(...) and split that by comma ,
Regex test: https://regex101.com/r/xFf39R/1
const answer = 'List(value1,value2,value3,value4)'
const res = /List\((.*)\)/.exec(answer)[1].split(',')
console.log(res)
Reference
RegExp.prototype.exec()
Return value
[...] The returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text.
Reading your data example... It seems like the answer is carrying a String as the single quote is presented in your data example.
answer:'List(value1,value2,value3,value4)'
^ ^
And the List(value1,value2,value3,value4) actually looks like some python List in system print.
Well, but this does not help in your direct question.
Assuming your want to get all four values into an array in javascript, do the followings
let data_example = {
...
'answer':'List(value1,value2,value3,value4)',
...
}
let answer_string = data_example['answer'].slice(5,-1)
let your_list = answer_string.split(',')
console.log(your_list)
//["value1","value2","value3","value4"]
But be careful... I assume your List() always start with 'List(' and end with ')'
See more on slice and split

How to get column_name and table_name from DML statement?

I am building an algorithm to mock DB operations.
I have one problem, how i can get Table name and column names from a DML statement?
i.e:
string = "SELECT id,name FROM USER_TBL"
string TABLE_NAME = getTableName(string); //this will return "USER_TBL"
array COLUMN_NAME = getColumnNames(string); //this will return ["id","name"]
If i consider these as string manipulation, how i can design algorithm to get table name & column names?
Currently i use following logic,
function getTableName(iString){
//find string between "FROM " to next " "(space) and return it
}
function getColumnNames(string){
//get string between "SELECT " and " FROM" and split string based on "," (comma) and return it
}
I wanted to know is there any algorithm already available for this(for reference)? What and all the cases i need to handle other than these?
I don't know an algorithm, but a few things that come to my mind:
Table name
- Tablenames can have aliases, but with your logic that should be OK
- Can be prefixed with the database name (dbname.tblname) -> so you might need to look for dots before returning the string
- Tablename can be a derived table --> select statement in brackets. In that case there is not really a simple to tablename derive
Column names
- Column names can have aliases, not sure how you want to handle that.
- What about calculations, conditions (Case when...) --> that is not just a column name but a combined or calculated value. In that case no real column name to retrieve
- You can have also select statements for single columns in the resultset
So overall, your approach works if there is no complexity in the sql queries, if yes, your logic might not return what you want to.
What about other statements, like UPDATE and INSERT? Is that also something that you want to parse?

insert into database with dynamic form with javascript (codeigniter) [duplicate]

This question already has an answer here:
PHP into database with dynamic form with javascript (codeigniter)
(1 answer)
Closed 7 years ago.
I build an app but I found new problem, I want to insert multiple data using javascript to add more form dynamically (then insert into table). Okay in my FIGURE, number 1,2,3 that's clear. But when I insert into the table , it can't succesfully. (number 4 is my function to insert data, but all of may form cannot insert (number 5) , only 1 data can insert ). what's wrong ? thanks
FIGURE
use for loop like this, your $_POST must be under loop.
for ($i = 0; $i < count($_REQUEST['heading']); $i++) {
$heading = $_POST["heading"][$i];
$address = $_POST["address"][$i];
$array_addmore[$i] =
array(
"heading" => urlencode($heading),
"address" => urlencode($address)
);
}

Construct mySQL query from dynamic select boxes

I've already been able to construct a mySQL query using select boxes. Starting with ajax to PHP like so.
html/js (relevant parts)
var call = true;
switch(parseInt($(this).val())) {
case 1:
cat_code ="ager";
sortv = "database_percent";
sorto = "asc";
break;
case 2:
cat_code ="ager";
sortv = "database_percent";
sorto = "desc";
break;
default:
cat_code ="ager";
sortv = "value";
sorto = "asc";
break;
}
if(call) {
$.ajax({
url: 'all_get_2.php',
type: 'GET',
dataType: 'JSON',
data: {cat_code: cat_code, sortvalue: sortv ,sortorder:sorto},
success: function(data) {
//stuff
}
})
PHP (relevant parts...just an example)
$whereCategory = isset($_GET['cat_code'])? "{$_GET['cat_code']}" : '';
$sortvalue = isset($_GET['sortvalue'])? "{$_GET['sortvalue']}" : '';
$sortorder = isset($_GET['sortorder'])? "{$_GET['sortorder']}" : '';
$sql = "select count(guid) from full_db2 where '{$whereCategory}' = '{$sortvalue}'' and example = '{$sortorder};";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
All's well. I mixed up some variables in this illustration, but that's not the issue. This returns the count for the attributes that the user selected from the selects. The selects are dynamically generated based on what the user selected in the previous select.
What if I wanted users to be able to select a bunch more attributes to add to the query. So, for example, instead of finding the count for the number of entries in the database (users) who's age is more than 40, they could add on more to this like users with age greater than 40 and married and have children.
I considered basically adding an option to add another set of select boxes (e.g., click a "+" and new set appears), but I quickly realized that I wouldn't be able to figure out how many selects were out there and a logical way to create a query.
What's the best possible way to allow users to select a (theoretically) unlimited number of attributes to construct in an single mySQL query?
I would use the HTML <select> & <option> tags to present the various SQL conditional operators (AND, OR, >, <, =, !=) along with your field/table names, then concatenate them together to build your query.
As mentioned in the comments, you could utilize the array capabilities like name="checkbox[]" and submit it as an HTML form (POST or GET) to simplify concatenation.
You will want to escape and sanitize anything sent to the database to avoid SQL injection as HTML pages can be edited client side. Without sanitization your entire database will be accessible to a savvy user. This can be as simple as verifying that the array contents matches actual table names or one of the conditional operators and then discarding if it doesn't match. Escaping using mysqli::escape_string (http://php.net/manual/en/mysqli.real-escape-string.php) is also a good idea.
I ended up having to redo this question after I was able to figure out a few things. Here's how I progressed and check the accepted answer to see how it all is done together:
Create array for PDO from variables passed from jquery

How to use update set in sqlite [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to update a table row using the below code
t.executeSql('UPDATE flatcomments SET BuildingCode = ?, FlatNo = ?, Comment = ?, Closed = ?, New = ?)',
[buildingcode, flatdescription, flatcomment.toUpperCase(), 1, 1]);
with no success. Where am i wrong
This is a nice PHP tutorial.
All SQLite commands will work for you.
<?php
# CREATING A TABLE
$dbname = 'base';
$mytable ="tablename";
$base= new SQLiteDatabase($dbname, 0666, $err);
if ($err) exit($err);
$query = "CREATE TABLE $mytable(
ID bigint(20) NOT NULL PRIMARY KEY,
post_author bigint(20) NOT NULL,
post_date datetime,
post_content longtext,
post_title text,
guid VARCHAR(255)
)";
$results = $base->queryexec($query);
# The SQL command CREATE TABLE defines the columns. It is sent to the SQLite manager by the PHP method queryExec() which returns true or false, depending on whether the operation is successful or not.
# See the code of the script sqlite-create-table.php.
# ADDING POSTS
# The table of posts that we just created will be filled, like in Wordpress, with the posts we write, each post corresponding to a row of the table.
# The SQL command: INSERT INTO allows to store the data.
$number = 1;
$title="My first post";
$content="The content of my post...";
$date = strftime( "%b %d %Y %H:%M", time());
$author=1;
$url = "http://www.lantian.eu";
$query = "INSERT INTO $mytable(ID, post_title, post_content, post_author, post_date, guid)
VALUES ('$number', '$title', '$content', '$author', '$date', '$url')";
$results = $base->queryexec($query);
# For the purposes of the tutorial, we place the contents of the post directly into variables. In practice these variables will be assigned from an t online or local ext editor, as shown in the CMS tutorial.
# The author is represented by the number 1 because Wordpress does not put the names in the posts table but in a separate table instead.
# The guid column contains the URL of the post that also serves as an ID unique.
# The INSERT command jas for first parameter the table name and in parentheses the list of columns to fill, then the parameter VALUE provides a list of values corresponding to the columns in the same order.
# Thus, post_title, which contains the titles, will has for value $title, the variable that was assigned the title of the post.
# The same queryExec method is used to send the request.
# Source code of the script sqlite-write.php.
# READING A POST
# You can access the contents of the database with the SELECT command.
$query = "SELECT post_title, post_content, post_author, post_date, guid FROM $mytable";
$results = $base->arrayQuery($query, SQLITE_ASSOC);
$arr = $results[0];
if($results)
{
$title = $arr['post_title'];
$content = $arr['post_content'];
$user = $arr['post_author'];
$date = $arr['post_date'];
$url = $arr['guid'];
}
# To the SELECT command is given the list of columns that you want get the content and lines will be assigned to $results array. Indeed, the arrayQuery PHP method returns an array of arrays, each representing a line of the table.
# In practice we will use instead other commands that we will see later to limit the resources usage.
# Data are retrieved in the associative array $arr, where the column names are keys and their content the values.
# Source code of the script sqlite-read.php.
# DELETING A TABLE
# The deletion of a table is made by the DROP TABLE command of SQL.
$query = "DROP TABLE $mytable";
$results = $base->queryexec($query);
# See the code sqlite-delete-table.php.
?>

Categories