so I've been trying to grab data from a name, like this
So my table look like this:
Table = database then ID, ip, name.
So when a name is entered I want to check if there is an IP attached to it in my database if there is then print all ip's else don't do anything..
This is very easy you didn't show what you tried.
A simple select would do it:
$stmt = $pdo->prepare('SELECT ip FROM `databases` WHERE name = :name');
$stmt->execute(array('name'=>$name));
$row = $stmt->fetch(FETCH_ASSOC);
then compare in PHP:
if($row['ip'] == $_SERVER['REMOTE_ADDR']){
//IP attached to it in my database
}
Related
I have following
case class Request(name:Option[String], age: Option[Int], address: Option[List[String]])
And I want to construct a query like this the conditions should apply if and only if the field is defined:
val req = Request(Some("abc"), Some(27), Some(List["add1", "add2"])
select name, age, email from user where name = "abc" AND age = 27 AND address in("add1", "add2");
I went through doobies documentation and found about fragments which allow me to do the following.
val baseSql: Fragment = sql"select name, age, email from user";
val nameFilter: Option[Fragment] = name.map(x => fr" name = $x")
val ageFilter: Option[Fragment] = age.map(x => fr" age = $x")
val addressFilter: Option[Fragment] = address.map(x => fr " address IN ( " ++ x.map(y => fr "$y").intercalate(fr",") ++ fr" )"
val q = baseSql ++ whereAndOpt(nameFilter, ageFilter, addressFilter)
from my understanding the query should look like this if all the fields are defined:
select name, age, email from user where name = "abc" AND age = 27 AND address in("add1","add2");
but the query looks like this:
select name, age, email from user where name = ? AND age = ? AND address in(?);
What is wrong here I am not able to find that.
Thanks in advance !!!!
Everything is fine.
Doobie prevents SQL injections by SQL functionality where you use ? in your query (parametrized query), and then pass the values that database should put into the consecutive ? arguments.
Think like this: if someone posted name = "''; DROP table users; SELECT 1". Then you'd end up with
select name, age, email from user where name = ''; DROP table users; SELECT 1
which could be a problem.
Since the database is inserting arguments for you, it can do it after the parsing of a raw text, when such injection is impossible. This functionality is used not only by Doobie but by virtually every modern library or framework that let you talk to database at level higher than plain driver.
So what you see is a parametrized query in the way that database will see it, you just don't see the parameters that will be passed to it.
I have a simple PostgreSql query that looks like:
$params = array();
if ($audienceId === x) {
// all teachers
$pullRecipients = $db -> prepare(
"SELECT email FROM app.employees WHERE emp_cat_id = 1 AND active is true");
}
$pullRecipients -> execute($params);
I'm running the queries based on a drop down select, so that if for example the user selects TEACHERS, the above query is run. How can I select for instance the emp_cat_id or even the category name TEACHERS without hard coding them in the query?
change statement to something like
SELECT email
FROM app.employees
WHERE emp_cat_id = ? AND active IS true
and make sure your $params is equal to something like array($POST["drop-down_value])
and if you want to allow text value - use join, something like:
SELECT email
FROM app.employees
WHERE emp_cat_id = (SELECT id FROM emp_cat WHERE name = ?)
AND active IS true
So i'm working on a laravel project where i pass some data to matlab and then matlab will edit them..everything works fine except the function of matlab that i wrote..
function show(a)
econ=database('datamining','root','');
curs=exec(con,'SELECT name FROM dataset_choices WHERE id = a');
curs = fetch(curs);
curs.Data
end
i want this function to display the name of the dataset the user choose..the problem is that it doesnt work writing just where id = a... but if i write for example where id=1 it works..
i tried to display just the a with disp(a) to see what is the value of the a and it is store the right id that user had choose..so how can i use it in my query??
Try:
a = num2str(a); % or make sure the user inputs a string instead
curs=exec(con,['SELECT name FROM dataset_choices WHERE id = ',a]);
If a = '1', then the brackets would print:
'SELECT name FROM dataset_choices WHERE id = 1'
Users of my site can submit post title and post content by form. The post title will be saved and converted to SEO friendly mode (eg: "title 12 $" -> "title-12"). this will be this post's url.
My question is if a user entered a title that is identical to previous entered title, the url's of those posts will be identical. So can be the new title be modified automatically by appending a number to the end of the title?
eg:
"title-new" -> "title-new-1" or if "title-new-1" present in db
convert it to "title-new-2"
I'm sorry I'm new to this, maybe it's very easy, Thanks for your help.
I'm using PDO.
when saving the post title you can query the db if it exists? If it exists the simply append a number and again query, if it again exists increment it by one and hence.
Do a select on your database for that title, and use rowCount() to check how many results you have. If the result is 0: you can add it, if the result is n, you add n to the title.
To append use something like this (not correct):
$count = $del->rowCount(); //Assuming this returns 1
if($count){
$title = $title . "-" . $count;
}
This will give you "theduplicatetitle-1"
thank you #Ratna & #Borniet for your answers. i'm posting explained code to any other user who want's it. if there is somrthing should be added or removed or better way please let me know.
//first i'm going to search the "new unchanged title name" whether it's present in db.
$newtitle= "tst-title";
$dbh = new PDO("mysql:host=localhost;dbname='dbname', 'usrname', 'password');
$stmt = $dbh->prepare("SELECT * FROM `tablename` WHERE `col.name` = ? LIMIT 1");
$stmt->execute(array($newtitle));
if ( $stmt->rowCount() < 1 ) {
// enter sql command to insert data
}
else {
$i='0';
do{
$i++;
$stmt = $dbh->prepare("SELECT * FROM `tablename` WHERE `url` = ? LIMIT 1");
$stmt->execute(array($newtitle.'-'.$i));
}
while($stmt->rowCount()>0);
// enter sql command to insert data
}
that's it. the reason i'm dividing in to two is because i want to add '-' to the url instead of just number.
this is my first question on stackOverflow.
I'm working with Corona and I'm having an issue accessing a SQLdb (I'm a bit of a SQL noob.)
I'm trying to access and return a value I've stored in the database.
Here's some code samples:
print("---------------- How I Create New Player Save Data")
local entry = [[CREATE TABLE IF NOT EXISTS playerData (key STRING PRIMARY KEY, content INTEGER);]]
db:exec(entry)
entry = [[INSERT INTO playerData VALUES ("LastLoginTime", 0);]]
db:exec( entry )
entry = [[INSERT INTO playerData VALUES ("Credits", 1000);]]
db:exec( entry )
entry = [[INSERT INTO playerData VALUES ("Level", 1);]]
db:exec( entry )
Now this function works, it will print everything in the db (i pass in 'dbName'):
--print all the table contents
for row in db:nrows("SELECT * FROM "..dbName) do
local text = row.key..": "..row.content
end
This doesn't work, it returns '0':
local grabCredits = "SELECT content FROM playerData WHERE key='Credits'"
local credits = db:exec(grabCredits)
print("-- value: "..credits)
Neither does this, also returns '0':
local grabCredits = "SELECT key FROM playerData WHERE content>=10"
local credits = db:exec(grabCredits)
print("-- value: "..credits)
I don't understand what I'm doing wrong. Maybe I need to use another function call on the db other than exec(). I realize I could iterate through the db every time I want to access a single entry, but that just seems inefficient.
Any help is very much appreciated.
If you want results, you must use some form of iterator. SQLite always returns rows for a query result.
This is similar to what I'm using to retrieve one result from my database and works well for me.
local query = "SELECT content FROM playerData WHERE key = 'Credits' LIMIT 1"
local queryResultTable = {}
local queryFunction = function(userData, numberOfColumns, columnValues, columnTitles)
for i = 1, numberOfColumns do
queryResultTable[columnTitles[i]] = columnValues[i]
end
end
db:exec(query, queryFunction)
for k,v in pairs(queryResultTable) do
print(k,v)
end