I going to create a website that can get as much as 6,000 alerts daily(those alerts containing up to 140-characters, that's approx. 30 words-tokens-). My question is if i have a function that verify if each token is already in the db, it false, do nothing, if true it get insert, and so on, but for each word it has to loop through the entire db for checking, how should i handle the connection? it is bad to open connections every time i need to check for a word?
function insertTag($tag){
$db = "test";
$user = "Eduardo";
$pass = "weaponx";
$host = "localhost";
$con = new mysqli($host, $user, $pass, $db);
$noInsert = false;
$result = $con->query("select TAG from TAGS");
$num_tags = $result->num_rows;
for($c=0; $c < $num_tags; $c++){
$row = $result->fetch_assoc();
echo "tag ". ($c+1) .": ". $row['TAG'] ."<br/>";
if ($fila['TAG'] === $tag){
echo "$tag: already exist.<br />";
$noInsert = true;
return;
}
else{
$noInsert = false;
}
}
if (!$noInsert){
$result2 = $con->query("insert into TAGS(TAG) values('$tag')");
echo "token $tag: inserted<br />";
}
}
$tags = "danger in detroit";
// insert word in the BD, only if new
for($i=0; $i < count($tags); $i++){
insertTag($tags[$i]);
}
should i use the mysqli version of persistent connection? if so how?
No no, don't do it that way :) Several points:
1) Open mysql connection at the beginning of your script, and do as many queries as you need without opening new connection for every query. (So opening connection need to be outside of your function)
2) You need to use indexes and mark your tag value in database as unique, in that case you can just INSERT every time, and if it is duplicate it will not get inserted. In order to create index for your table you need to use your favorite sql manager, or just do a query, you can read here more:
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
But in short you need to make column that represents your tag name to be unique ('TAG' in 'TAGS' table), and you need to put your con->query statement inside a try catch block, as it will probably throw exception on duplicate and you need to handle that.
3) I think you are inserting wring values as tags, you are using letters instead of words, is it supposed to be like that?
4) your query look incorrect, does it work?
do something like this (obviously after you have added unique index to your table):
function insertTag($con, $tag){
try {
$con->query("INSERT INTO `TAGS` (TAG`) values('$tag')");
echo "token $tag: inserted<br />";
} catch (Exception $e) {
echo "token $tag: NOT inserted<br />";
}
}
$tags = "danger in detroit";
// will create array of words
$tags = explode(' ', $tags);
$db = "test";
$user = "Eduardo";
$pass = "weaponx";
$host = "localhost";
$con = new mysqli($host, $user, $pass, $db);
// insert word in the DB, only if new
for($i=0; $i < count($tags); $i++) {
insertTag($con, $tags[$i]);
}
Also, I think this might be even done with ONE INSERT query for all tags, but I am not 100% sure, need to check.
Connecting and disconnecting from the database is expensive; for performance, you want to avoid connection "churning".
(In our J2EE web servers, we implement connection pools which are a collection of validated database sessions. The applications can "churn" through the connection pool, retrieving and returning connections, but the actual database session stays connected.)
So, to answer your question, it's a bad design to churn through database connections. A better approach is to connect once at the beginning of the process, pass the handle of that database connection to the functions that need it, and then disconnect at the end of the process.
The answer from Avetis Zakharyan provides a good approach. I totally agree with him that there is no need to run a separate SELECT statement. It's much more efficient to have the INSERT statement check whether the value exists or not.
This approach reduces the number of roundtrips to the database, AND it also works across multiple concurrent sessions where two (or more) sessions may be running a SELECT to check for the existence of tag, and both sessions don't find it, and when both sessions insert the same tag. A UNIQUE constraint on the column would avoid duplicates; using INSERT IGNORE avoids throwing an exception, but still...
My preferred approach would be to use a SQL statement that only attempts to insert a row if a matching row doesn't already exist:
INSERT INTO tags (tag)
SELECT v.tagval
FROM (SELECT :tag AS tagval) v
LEFT JOIN tags d ON d.tag = v.tagval
WHERE d.tag IS NULL
This is not dependent on a UNIQUE constraint on the tag columns; and it's not dependent on the existence of any index, but an index with a leading column of tag would be desirable for improved performance.
(The SELECT can be run separately, for testing.)
The query is a classic antijoin... "return rows from v for which there is no match in d".
With PDO, use bind parameters, rather than including values in the SQL text.
$sql = "INSERT INTO tags (tag)
SELECT v.tagval
FROM (SELECT :tag AS tagval) v
LEFT JOIN tags d ON d.tag = v.tagval
WHERE d.tag IS NULL ";
$stmt=$conn->prepare($sql);
$stmt->bindParam(":tag",$tag);
$stmt->execute();
(Note: if the characterset of the client differs from the characterset of the target column, the conversion may need to be explicit. For example, if the client characterset is UTF8 and the column is latin1, then:
FROM (SELECT CONVERT(:tag AS latin1) AS tagval) v
Related
Im not trying to use a loop. I just one one value from one column from one row. I got what I want with the following code but there has to be an easier way using PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=advlou_test', 'advlou_wh', 'advlou_wh');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$userid = 1;
$username = $conn->query("SELECT name FROM `login_users` WHERE username='$userid'");
$username2 = $username->fetch();
$username3 = $username2['name'];
echo $username3;
This just looks like too many lines to get one value from the database. :\
You can use fetchColumn():
$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?");
$q->execute([$userid]);
$username = $q->fetchColumn();
You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn() method also comes in handy for fetching a single value from the query
function getSingleValue($conn, $sql, $parameters)
{
$q = $conn->prepare($sql);
$q->execute($parameters);
return $q->fetchColumn();
}
Then you can simply do:
$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]);
and it will get you the desired value.
So you need to create that function just once, but can reuse it for different queries.
This answer has been community edited addressing security concerns
Just like it's far too much work to have to get into your car, drive to the store, fight your way through the crowds, grab that jug of milk you need, then fight your way back home, just so you can have a milkshake.
All of those stages are necessary, and each subsequent step depends on the previous ones having been performed.
If you do this repeatedly, then by all means wrap a function around it so you can reuse it and reduce it down to a single getMyValue() call - but in the background all that code still must be present.
I have never asked anything on one of these before, I could usually
think of or find a way that was posted for ideas.
I tried ways I thought of, tried using a CASE example that looked like it should work and no go. It won't update in any case.
OK here is what I am trying to do:
$Mysqlinfo="INSERT INTO `$PNum` (P_IDNum, P_Name, Raw_Time, Total_Time, T_Mode)
VALUES ('$PersId', '$_POST[PersonaName]', '$Stats_Vals[1]', '$Stats_Vals[2]', '$Stats_Vals[5]')
ON DUPLICATE KEY UPDATE Car_Model='$Stats_Vals[1]', Total_Time='$Stats_Vals[5]', Raw_Time='$Stats_Vals[7]', T_Mode='$Stats_Vals[2]' (there was originally the "; at end here)
***WHERE Raw_Time > '$Stats_Vals[7]'";***
(There were more names there but I removed some so it was not sooo loong, so don't mind so much the $Stats_Vals numbers as the structure).
The thing works without the WHERE at the end except it always will INSERT or UPDATE, I know Where does not work with ON DUPLICATE KEY unfortunately so what is an easy equivalent?
It has to chk for the Val and do NOTHING if the condition is NOT True.
Oh yeah it is formatted for use in a PHP script. :0)
Thanks much for any help!
Edit - Here is most of the PHP/sql code without the condition I am trying to achieve, it is called by an application:
<?php
hostname and
database info here
Variables, $_POST... etc.
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Connection to Server successful!" . PHP_EOL; <for testing from web
}
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can\'t select database: ' . mysql_error());
}
else {
echo "Database successfully selected!". PHP_EOL;
$Mysqlinfo="INSERT INTO `$PNum` (P_IDNum, P_Name, Raw_Time, Total_Time, T_Mode)
VALUES ('$PersId', '$_POST[PersonaName]', '$Stats_Vals[1]', '$Stats_Vals[2]', '$Stats_Vals[5]')
ON DUPLICATE KEY UPDATE Car_Model='$Stats_Vals[1]', Total_Time='$Stats_Vals[5]', Raw_Time='$Stats_Vals[7]', T_Mode='$Stats_Vals[2]'";
if (!mysql_query($Mysqlinfo,$link))
{
mysql_close($link);
die('Error: ' . mysql_error());
}
}
mysql_close($link);
?>
it works except for not following the condition of only updating if Raw_Time is less.
Thanks again!
If you want to make the update conditional, then I'm afraid you can't do it with INSERT...ON DUPLICATE KEY UPDATE.... You'll have to do it in two or more queries. And in order to make it atomic, you'll have to use LOCK TABLES:
$primarykey = 'whatever';
query("LOCK TABLES mytable WRITE;");
$count = query("SELECT COUNT(*) FROM mytable WHERE id=?;", $primarykey);
if($count>0) // the ID already exists
{
$time = query("SELECT Raw_time FROM mytable WHERE id=?;", $primarykey);
if($time>$Stats_Vals[7])
query("UPDATE mytable SET ... WHERE id=?;", $primarykey);
}
else
query("INSERT INTO mytable ...");
query("UNLOCK TABLES;");
A couple of notes:
I'm calling some made up function query here because I don't know what method you're using to execute queries. I've also abbreviated some of the queries because I'm too lazy to copy all your code. You'll need to adjust the code according to your needs.
I've also used ? for parameters in the queries - this is good practice to prevent SQL injection.
The LOCK TABLES statement is there to ensure that no other process can delete the record you're working with between the time you check for the record's existence (SELECT COUNT(*)...) and the time you update. If that were to happen, your code will cause an error.
There is no single-query solution, you either have to retrieve the value of the Raw_Time column for the appropriate record (if exists) and evaluate that in your PHP script; or create a stored procedure for the task.
By the way, look out for security issues, like SQL Injection, when inserting values in your query given by the users.
I was wondering if you think this is possible:
Ok so I have a database storing usernames and I would like to echo the admins which are inside a file called admins.php IF they match the usernames inside the database so far I have got:
admins.php;
$admins = array("username","username2","username3");
and
$users="SELECT username from usrsys";
$query_users=mysql_query($users);
while loop here.
The while loop should hopefully echo the users which matches the admins.php file. I assume I should use something like (inarray()), but I am really not sure.
You should definitely use IN clause in your SQL to do this. Selecting everything from the table in order to determine in PHP if it contains the user names you're looking for makes no sense and is very wasteful. Can you imagine what would happen if you had a table of 1 million users and you needed to see if two of them were on that list? You would be asking your DBMS to return 1 million rows to PHP so that you can search through each of those names and then determine whether or not any of them are the ones you're looking for. You're asking your DBMS to do a lot of work (send over all the rows in the table), and you're also asking PHP to do a lot of work (store all those rows in memory and compute a match), unnecessarily.
There is a much more efficient and faster solution depending on what you want.
First, if you only need to know that all of those users exist in the table then use SELECT COUNT(username) instead and your database will return a single row with a value for how many rows were found in the table. That way you have an all or nothing approach (if that's what you're looking for). Either there were 3 rows found in the table and 3 elements in the array or there weren't. This also utilizes your table indexes (which you should have properly indexed) and means faster results.
$admins = array("username","username2","username3");
// Make sure you properly escape your data before you put in your SQL
$list = array_map('mysql_real_escape_string', $admins);
// You're going to need to quote the strings as well before they work in your SQL
foreach ($list as $k => $v) $list[$k] = "'$v'";
$list = implode(',', $list);
$users = "SELECT COUNT(username) FROM usrsys WHERE username IN($list)";
$query_users = mysql_query($users);
if (!$query_users) {
echo "Huston we have a problem! " . mysql_error(); // Basic error handling (DEBUG ONLY)
exit;
}
if (false === $result = mysql_fetch_row($query_users)) {
echo "Huston we have a problme! " . mysql_error(); // Basic error handling (DEBUG ONLY)
}
if ($result[0] == count($admins)) {
echo "All admins found! We have {$result[0]} admins in the table... Mission complete. Returning to base, over...";
}
If you actually do want all the data then remove the COUNT from the SQL and you will simply get all the rows for those users (if any are found).
$admins = array("username","username2","username3");
// Make sure you properly escape your data before you put in your SQL
$list = array_map('mysql_real_escape_string', $admins);
// You're going to need to quote the strings as well before they work in your SQL
foreach ($list as $k => $v) $list[$k] = "'$v'";
$list = implode(',', $list);
$users = "SELECT username FROM usrsys WHERE username IN($list)";
$query_users = mysql_query($users);
if (!$query_users) {
echo "Huston we have a problem! " . mysql_error(); // Basic error handling (DEBUG ONLY)
exit;
}
// Loop over the result set
while ($result = mysql_fetch_assoc($query_users)) {
echo "User name found: {$result['username']}\n";
}
However, I really urge you to reconsider using the old ext/mysql API to interface with your MySQL database in PHP since it is deprecated and has been discouraged from use for quite some time. I would really urge you to start using the new alternative APIs such as PDO or MySQLi and see the guide in the manual for help with choosing an API.
In PDO, for example this process would be quite simple with prepared statements and parameterized queries as you don't have to worry about all this escaping.
There's an example in the PDOStatement::Execute page (Example #5) that shows you just how to do use the IN clause that way with prepared statements... You can then reuse this statement in other places in your code and it offers a performance benefit as well as making it harder for you to inadvertently expose yourself to SQL injection vulnerabilities.
// Connect to your database
$pdo = new PDO("mysql:dbname=mydb;host=127.0.0.1", $username, $password);
// List of admins we want to find in the table
$admins = array("username","username2","username3");
// Create the place holders for your paratmers
$place_holders = implode(',', array_fill(0, count($admins), '?'));
// Create the prepared statement
$sth = $dbh->prepare("SELECT username FROM usrsys WHERE username IN ($place_holders)");
// Execute the statement
$sth->execute($admins);
// Iterate over the result set
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo "We found the user name: {$row['username']}!\n";
}
Your PHP code even looks so much better with PDO :)
Just include admins.php file and use the next construction in your loop:
while ($row = mysql_fetch_array($users)) {
if (in_array($users[0], $admins))
echo $users[0];
}
Try this:
<?php
# include admins.php file that holds the admins array
include "admins.php";
# join all values in the admins array using "," as a separator (to use them in the sql statement)
$admins = join(",", $admins);
# execute the query
$result = mysql_query("
SELECT username
FROM usrsys
WHERE username IN ($admins)
");
if ($result) {
while ($row = mysql_fetch_array($result)) {
echo $row["username"] . "<br>";
}
}
?>
If your looking for syntax to pull in only the users from your $admins array then you could use something like:
$users="SELECT username FROM usrsys WHERE username IN ('".join("','",$admins)."')";
Where the php function JOIN will print username,username2,username3. Your resulting MySQL statement will look like:
SELECT username FROM usrsys WHERE username IN ('username','username2','username3')
Alternatively, if your looking to iterate through your $query_vars array and separate your admins from non-admins then you could use something like:
<?php
while($row = mysql_fetch_assoc($query_users)){
if(in_array($row['username'],$admins)){
//do admin stuff here
}else{
//do NON-admin stuff here
}
}?>
I want to show all text messages from db where id=$e ($err is an array).
Inserted the query into the foreach loop, it works well but it does extra work (does query for every value of array).
Is there any other way to do it (i mean extract query from foreach loop)?
My code looks like this.
foreach ($err as $e)
{
$result = $db -> query("SELECT * from err_msgs WHERE id='$e'");
$row = $result -> fetch_array(MYSQLI_BOTH);
echo "<li><span>".$row[1]."</span></li>";
}
It is much more efficient to do this with implode() because it will only result in one database query.
if (!$result = $db->query("SELECT * FROM `err_msgs` WHERE `id`='".implode("' OR `id`='",$err)."'")) {
echo "Error during database query<br />\n";
// echo $db->error(); // Only uncomment this line in development environments. Don't show the error message to your users!
}
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<li><span>".$row[1]."</span></li>\n";
}
Check the SQL IN clause.
Firstly, a bit of a lecture: embedding strings directly into your queries is going to cause you trouble at some point (SQL injection related trouble to be precise), try to avoid this if possible. Personally, I use the PDO PHP library which allows you to bind parameters instead of building up a string.
With regard to your question, I'm not sure I have understood. You say that it does extra work, do you mean that it returns the correct results but in an inefficient way? If so then this too can be addressed with PDO. Here's the idea.
Step 1: Prepare your statement, putting a placeholder where you currently have '$e'
Step 2: Loop through $err, in the body of the loop you will set the place holder to be the current value of $e
By doing this you not only address the SQL injection issue, you can potentially avoid the overhead of having to parse and optimise the query each time it is executed (although bear in mind that this may not be a significant overhead in your specific case).
Some actual code would look as follows:
// Assume that $dbdriver, $dbhost and $dbname have been initialised
// somewhere. For a mysql database, the value for $dbdriver should be
// "mysql".
$dsn = "$dbdriver:host=$dbhost;dbname=$dbname";
$dbh = new PDO($dsn, $dbuser, $dbpassword);
$qry = "SELECT * from err_msgs WHERE id = :e"
$sth = $dbh->prepare($qry);
foreach ($err as $e) {
$sth->bindParam(":e", $e);
$sth->execute();
$row = $sth->fetch();
// Prints out the *second* field of the record
// Note that $row is also an associative array so if we
// have a field called id, we could use $row["id"] to
// get its value
echo "<li><span>".$row[1]."</span></li>";
}
One final point, if you want to simply execute the query once, instead of executing it inside the loop, this is possible but again, may not yield any performance improvement. This could be achieved using the IN syntax. For example, if I'm interested in records with id in the set {5, 7, 21, 4, 76, 9}, I would do:
SELECT * from err_msgs WHERE id IN (5, 7, 21, 4, 76, 9)
I don't think there's a clean way to bind a list using PDO so you would use the loop to build up the string and then execute the query after the loop. Note that a query formulated in this way is unlikely to give you any noticable performance improvment but it really does depend on your specific circumstances and you'll just have to try it out.
You can do this much simpler by doing
$err_csv = implode("','",$err);
$sql = "SELECT FROM err_msgs WHERE id IN ('$err_csv')";
$result = $db -> query($sql);
while ($row = $result -> fetch_array(MYSQLI_BOTH))
{
echo "<li><span>".$row[1]."</span></li>";
}
That way you don't have to keep sending queries to the database.
Links:
http://php.net/manual/en/function.implode.php
I have two dynamic tables (tabx and taby) which are created and maintained through a php interface where columns can be added, deleted, renamed etc.
I want to read all columns simulataneously from the two tables like so;-
select * from tabx,taby where ... ;
I want to be able to tell from the result of the query whether each column came from either tabx or taby - is there a way to force mysql to return fully qualified column names e.g. tabx.col1, tabx.col2, taby.coln etc?
In PHP, you can get the field information from the result, like so (stolen from a project I wrote long ago):
/*
Similar to mysql_fetch_assoc(), this function returns an associative array
given a mysql resource, but prepends the table name (or table alias, if
used in the query) to the column name, effectively namespacing the column
names and allowing SELECTS for column names that would otherwise have collided
when building a row's associative array.
*/
function mysql_fetch_assoc_with_table_names($resource) {
// get a numerically indexed row, which includes all fields, even if their names collide
$row = mysql_fetch_row($resource);
if( ! $row)
return $row;
$result = array();
$size = count($row);
for($i = 0; $i < $size; $i++) {
// now fetch the field information
$info = mysql_fetch_field($resource, $i);
$table = $info->table;
$name = $info->name;
// and make an associative array, where the key is $table.$name
$result["$table.$name"] = $row[$i]; // e.g. $result["user.name"] = "Joe Schmoe";
}
return $result;
}
Then you can use it like this:
$resource = mysql_query("SELECT * FROM user JOIN question USING (user_id)");
while($row = mysql_fetch_assoc_with_table_names($resource)) {
echo $row['question.title'] . ' Asked by ' . $row['user.name'] . "\n";
}
So to answer your question directly, the table name data is always sent by MySQL -- It's up to the client to tell you where each column came from. If you really want MySQL to return each column name unambiguously, you will need to modify your queries to do the aliasing explicitly, like #Shabbyrobe suggested.
select * from tabx tx, taby ty where ... ;
Does:
SELECT tabx.*, taby.* FROM tabx, taby WHERE ...
work?
I'm left wondering what you are trying to accomplish. First of all, adding and removing columns from a table is a strange practice; it implies that the schema of your data is changing at run-time.
Furthermore, to query from the two tables at the same time, there should be some kind of relationship between them. Rows in one table should be correlated in some way with rows of the other table. If this is not the case, you're better off doing two separate SELECT queries.
The answer to your question has already been given: SELECT tablename.* to retrieve all the columns from the given table. This may or may not work correctly if there are columns with the same name in both tables; you should look that up in the documentation.
Could you give us more information on the problem you're trying to solve? I think there's a good chance you're going about this the wrong way.
Leaving aside any questions about why you might want to do this, and why you would want to do a cross join here at all, here's the best way I can come up with off the top of my head.
You could try doing an EXPLAIN on each table and build the select statement programatically from the result. Here's a poor example of a script which will give you a dynamically generated field list with aliases. This will increase the number of queries you perform though as each table in the dynamically generated query will cause an EXPLAIN query to be fired (although this could be mitigated with caching fairly easily).
<?php
$pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
function aliasFields($pdo, $table, $delim='__') {
$fields = array();
// gotta sanitise the table name - can't do it with prepared statement
$table = preg_replace('/[^A-z0-9_]/', "", $table);
foreach ($pdo->query("EXPLAIN `".$table."`") as $row) {
$fields[] = $table.'.'.$row['Field'].' as '.$table.$delim.$row['Field'];
}
return $fields;
}
$fieldAliases = array_merge(aliasFields($pdo, 'artist'), aliasFields($pdo, 'event'));
$query = 'SELECT '.implode(', ', $fieldAliases).' FROM artist, event';
echo $query;
The result is a query that looks like this, with the table and column name separated by two underscores (or whatever delimeter you like, see the third parameter to aliasFields()):
// ABOVE PROGRAM'S OUTPUT (assuming database exists)
SELECT artist__artist_id, artist__event_id, artist__artist_name, event__event_id, event__event_name FROM artist, event
From there, when you iterate over the results, you can just do an explode on each field name with the same delimeter to get the table name and field name.
John Douthat's answer is much better than the above. It would only be useful if the field metadata was not returned by the database, as PDO threatens may be the case with some drivers.
Here is a simple snippet for how to do what John suggetsted using PDO instead of mysql_*():
<?php
$pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$query = 'SELECT artist.*, eventartist.* FROM artist, eventartist LIMIT 1';
$stmt = $pdo->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch()) {
foreach ($row as $key=>$value) {
if (is_int($key)) {
$meta = $stmt->getColumnMeta($key);
echo $meta['table'].".".$meta['name']."<br />";
}
}
}