I want to search in a database with variable positions. The variables are created here:
&numbers //= user input
&naar // = user input
$number = range($numbers+1, $naar -1); //define the range between the inputs
foreach ($number as $key=>$val){
$number[$key] = $letter.$val;} //define the array
$string = implode (' ',$number); // make a string from the array
This works fine. The output is a string that contains a minimum of 0 outputs and a maximun of 7 outputs. For example: A2 A3 A4 A5
I want the database to search if something is at one of the generated positions. Ive got this already:
$query="select chess_id from stelling where positie=\"".$number."\"";
$result = mysql_query($query, $connection);
$spring = 0;
if(mysql_num_rows($result)>0)
{
$spring = mysql_result($result, 0);
}
echo "$spring";
With this code only the last generated $string output will be checked. How can i let the database check all generated string code? For example:
$string = `A2 A3 A4 A5`
$query="select chess_id from stelling where positie=\"".$number."\"";
will only check A5
sample rows from table:
wt,A1
wp,A2
wl,A3
wq,A4
Well I am not shure what exactly is your problem but why don't you use IN statement ?
$string = '(`' . implode('`, `',$number) . '`)';
$query="select chess_id from stelling where positie IN {$string}";
Related
I'd like to convert an array to string with newline characters for simplest text formatting. The array is a result of a mysql select query and I suppose I need a loop which uses the implode function to convert to string and separate the fields with something (i.e. " * ") and at the end of each row ads a newline character.
sample output
2018-06-22 * meeting * They didn't want to buy anythin
2018-06-23 * * called and wanted to buy something
2018-06-24 * meeting * Gave specification
I was thinking something like this (but I am wrong and this is why I ask):
$Diary =''; // start with empty string
$array = mysqli_fetch_array($fetch);// fetched already
$length = count($array);
for ($x = 0; $length; $x++ + 3) {
$temparray = // use a temp array for one row only
$Diary = // increment a string until the end of the row, add newline at the end
}
And here's the answer. "Thanks" for all the downvoting.
$Diary ='';
$query = 'SELECT tb2_date, tb2_note, tb2_entry from DiaryTable WHERE tb2_tb1ID =
"'.$HiddenID.'" ORDER BY tb2_date DESC';
$resulto = mysqli_query($dbc, $query);
while ($rows = mysqli_fetch_row($resulto)) {
$rowimploded = implode(' ** ', $rows);
$newline = "\r\n";
$Diary = $Diary.$rowimploded.$newline;
}
mysqli_free_result($resulto);
// echo $Diary or whatever...
I am trying to pull a list of words from the database, create a unique three-word combination in the form $word1.$word2.$word3, and assign it to a star.
I want to avoid duplicate combinations - I want each star to have a unique three-word identifier.
My current method involves creating an array of all possible three-word combinations and then deleting each combination from the array once it has been assigned to a star. I intend, however, to use a few-thousand words in my word list, which means this array will contain tens of billions of combinations, so this method seems incredibly inefficient.
How can I achieve this more effectively? My initial thoughts are that I should loop through each star, create and assign a three-word combination, then add the combo to an array, and for each star, check if the newly generated combo is in the array.
Code
<?php
// Initiate connection to the database...
$db = mysqli_connect('localhost', 'root', '', 'stellar');
// Query database of words
$words_sql = "SELECT * FROM words";
$words_res = mysqli_query($db, $words_sql)or die(mysqli_error());
// Create array of words
$words = array();
// Loop through each word from the database and add each to an array
while($row = mysqli_fetch_array($words_res)){
$words[] = $row['word'];
}
// Create array of all possible three-word combinations, from which we will randomly select our combinations
$triplets = array();
foreach ($words as $word1){
foreach ($words as $word2){
foreach($words as $word3){
if ($word1 !== $word2 && $word2 !== $word3 && $word1 !== $word3){
$triplets[] = "$word1.$word2.$word3";
}
}
}
}
// Pull all stars from database
$stars_sql = "SELECT * FROM stars";
$stars_res = mysqli_query($db, $stars_sql)or die(mysqli_error());
// Loop through every star in the array
while($row = mysqli_fetch_array($stars_res)){
// Store the star name and star_id in variables
$star = $row['star_name'];
$star_id = $row['star_id'];
// Set $three_words as a random combination from the array of possible combinations...
$ran_num = array_rand($triplets);
$three_words = $triplets[$ran_num];
// ...and remove this particular combination, in order to prevent repating combinations
array_splice($triplets, $ran_num, 1);
// Attach the random 3-word combination to the star
echo $star.' '.$three_words.'<br/><br/>';
}
?>
There is (possibly) a minor tweak you can make to get MySQL to do some of the heavy lifting for you.
$words_sql = "SELECT CONCAT(w1.word,'.',w2.word,'.',w3.word) as triplet
FROM (words w1 JOIN words w2 ON w1.word != w2.word)
JOIN words w3 ON w3.word != w1.word AND w3.word != w2.word";
$words_res = mysqli_query($db, $words_sql)or die(mysqli_error());
// Create array of words
$words = array();
// Loop through each word from the database and add each to an array
while($row = mysqli_fetch_array($words_res)){
$triplets[] = $row['triplet'];
}
This is probably as good as you're going to get because by the end of the process you'll have assigned all triplets to a star, which means whether you pre-generate the triplets or generate them later, you'll end up generating them all anyway.
Now there is an alternative solution for the case where the number of triplets are much much greater than the number of stars you need to name: say you have 2.5 million stars but 2000 words (or 8 billion triplets). In this case the stars are a tiny fraction of your possible triplets so you can do the following:
$words = array();
// Loop through each word from the database and add each to an array
while($row = mysqli_fetch_array($words_res)){
$words[] = $row['word'];
}
// Pull all stars from database
$stars_sql = "SELECT * FROM stars";
$stars_res = mysqli_query($db, $stars_sql)or die(mysqli_error());
// Loop through every star in the array
$used = [];
while($row = mysqli_fetch_array($stars_res)){
// Store the star name and star_id in variables
$star = $row['star_name'];
$star_id = $row['star_id'];
do {
//Generate non-repeating triplet of words (sample without replacement?)
$word1 = array_rand($words);
do {
$word2 = array_rand($words);
} while ($word2 == $word1);
do {
$word3 = array_rand($words);
} while ($word3 == $word2 || $word1 == $word3);
$triplet = $words[$word1].".".$words[$word2].".".$words[$word3];
} while (isset($used[$triplet])); //Try again if we've already used it. Very unlikely.
$used[$triplet] = true; //Keep track of what we've used.
echo $star.' '.$triplet.'<br/><br/>';
}
In the second case, this works because the chance we generate the same triplet twice is very small because of the possible number of triplets and the fact that we're using only a tiny fraction of them in total.
I have a file like this:
FG 09097612 DN 6575 HL 879797
BHC 09097613 DN 6576 HL 879798
FG 09097614 DN 6577 IOPPP 879799
FG 09097614 DN 6577 IOPPP 879800
with its logic that never changes line by line, it is always the same logic.
I would create an array taking the first 2 characters as a variable "nation", then the first 8 characters as a var "prize", then 2 other characters as "player" and so on and create a record in the database for each line.
I am using this code (THE CODE IN TEH EDIT ABOVE IS CHANGED), but not being a csv with delimitation with comma or tab I don't know how to do.
ini_set("auto_detect_line_endings", 1);
$current_row = 1;
$handle = fopen("upload/import.txt", "r");
while ( ($csv_data = fgetcsv($handle, 10000, "\t") ) !== FALSE )
{
$number_of_fields = count($csv_data);
if ($current_row == 1) {
}
else {
}
fclose($handle);
}
I want to put theese var in a record of database, each var in each column.
What do you recommend?
Obviously I can not change the original txt file.
HOW TO SAVE IN DATABASE?
If I use this code (from one answer above):
$lines = file("upload/import.txt");
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
I use this code:
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation) VALUES ('".$nation."')";
echo "<br>Inserted: ".$nation."<br>";
$result = odbc_exec($dbhandle, $query);
But it seems to me that this code is too heavy to be done in a foreach? Is not it?
1.In this situation, delimiter changes because of the formatting so I suggest you treat it as a string but not a csv.
FG 09097612 DN 6575 HL 879797
BHC 09097613 DN 6576 HL 879798
FG 09097614 DN 6577 IOPPP 879799
FG 09097614 DN 6577 IOPPP 879800
$lines = file("upload/import.txt");
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
}
2.Or if you insist on using csv parser, you should make consecutive spaces into one before you actually use fgetscsv:
$tempfile = "tmp/temp".microtime()."csv"; // a temp folder where you have write authority, `microtime()` here is used to generate a unique filename.
$content = file_get_contents("upload/import.txt");
while(strpos($content," ") !== false) {
// while consecutive spaces exist
$content = str_replace(" ", " ", $content);
}
file_put_contents($tempfile, $content);
Then you can treat it as a normal csv file with space delimiter like this:
$handle = fopen($tempfile, "r");
$current_row = 1;
while ( ($csv_data = fgetcsv($handle, 10000, " ") ) !== FALSE )
{
$number_of_fields = count($csv_data);
// ...
}
fclose($handle);
After you finish this , delete the temp file like this:
unlink($tempfile);
And it is better to do the insert only once than create and run the insert query in a foreach loop, so instead of adding
$query = "INSERT INTO TEST (nation) VALUES ('".$nation."')";
$result = odbc_exec($dbhandle, $query);
in each loop, which produces
INSERT INTO TEST (nation) VALUES ('FG');
INSERT INTO TEST (nation) VALUES ('BHC');
INSERT INTO TEST (nation) VALUES ('FG');
INSERT INTO TEST (nation) VALUES ('FG');
...
, it is more reasonable to create the query like this
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation) VALUES \n";
$row = array(); // query for each line
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
$row []= "(".$nation.")";
}
$query .= implode(",\n",$row).";";
$result = odbc_exec($dbhandle, $query);
If you echo $query, you should get something like this:
INSERT INTO TEST (nation) VALUES
('FG'),
('BHC'),
('FG'),
('FG');
which is much more light to run insert query every line.
PS: Please be careful that mysql has a limited query length. If the query is longer than max length, you will get an error , something like 'Mysql has gone away...'. I haven't much experience in using ms-sql server but there should be a same limit.
In this situation, you should split the query in a proper way. For example, run and clear the query every 10000 lines like this:
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass) or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation) VALUES \n";
$row = array(); // query for each line
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
$row []= "('".$nation."')";
if($lineNum % 10000 == 9999){
// run and reproduce the query every 10000 lines
$query .= implode(",\n",$row).";";
// put 'echo $query;' here would help you understand the design
$result = odbc_exec($dbhandle, $query);
// It is better to check the result here if it success
// The query has been run so it should be initialized again, so is $row.
$query = "INSERT INTO TEST (nation) VALUES \n";
$row = array(); // query for each line
}
}
$query .= implode(",\n",$row).";";
$result = odbc_exec($dbhandle, $query);
Answer to 'I need now to check if in the file there are lines with the same nation, in this example "FG" and sum the $prize of each "FG" and save only the total in prize and not all the lines of FG? '
Of course you can do that, since I don't know your table or how you would like to save your other data so I will just provide a sample with only nation and price:
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation, prize) VALUES \n";
$row = array(); // data for each line
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$row[$nation] = !empty($row[$nation])? $row[$nation] + (int)$prize : 0 ; // make sure prize is an interger in your file
}
// Since there are not so much nations in the world, I don't think it is necessary to worry about the max query length
$query_row = array(); // query for each line
foreach($row as $nation => $sum_prize){
$query_row []= "('".$nation."','".$sum_prize."')";
}
$query .= implode(",\n",$query_row).";";
$result = odbc_exec($dbhandle, $query);
Try this:
$handle = fopen("upload/import.txt", "r");
$current_row = 1;
while(!feof($handle)){
$str=fgets($handle);//read one line of the file
$str=str_replace(" "," ",$str);//reduce all consecutive spaces to single space
$arr=explode(" ",$str);
if ($current_row == 1) {
}
else {
}
}
fclose($handle);
Now the array $arr will contain the strings {"FG","09097612,"DN","6575","HL","879797"} (after reading the first line). You can use this array to access the values and insert them in DB.
EDIT:
I understand that you want to have an array called "nation" which will contain values {"FG","BHC","FG","FG"}, and the same for prize and other variables. Try this code:
$nation=array();
$prize=array();
$player=array();
$handle = fopen("upload/import.txt", "r");
$current_row = 1;
while(!feof($handle)){
$str=fgets($handle);//read one line of the file
$str=str_replace(" "," ",$str);//reduce all consecutive spaces to single space
$arr=explode(" ",$str);
//now insert values in respective arrays
array_push($nation,$arr[0]);
array_push($prize,$arr[1]);
array_push($player,$arr[2]);
//and so on
if ($current_row == 1) {
}
else {
}
}
fclose($handle);
Now you can use the arrays $nation, $prize and $player. You can create arrays for the other values in the same manner.
Hope this helps.
I have a file like this
FG 09097612 DN 6575 HL 879797
BHC 09097613 DN 6576 HL 879798
FG 09097614 DN 6577 IOPPP 879799
FG 09097614 DN 6577 IOPPP 879800
and I import it in mysql with
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation) VALUES \n";
$row = array(); // query for each line
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
$row []= "(".$nation.")";
}
$query .= implode(",\n",$row).";";
$result = odbc_exec($dbhandle, $query);
What I need now is to check if in the file there are lines with the same nation, in this example "FG" and sum the $prize of each "FG" and save only the total in prize and not all the lines of FG?
If you need to do this in php I would save the rows in an array keyed by the nation, and each time check if that key already exists and if so just increment the prize.
Something like this:-
<?php
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation, prize) VALUES \n";
$row = array(); // query for each line
foreach($lines as $lineNum => $line )
{
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
if (array_key_exists($nation, $row))
{
$row[$nation]['prize'] += $prize;
}
else
{
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
$row[$nation]= array('nation'=>$nation, 'prize'=>$prize);
}
}
array_walk($row, function($v, $k){return "(".$v['nation'].", ".$v['prize'].")";});
$query .= implode(",\n",$row).";";
$result = odbc_exec($dbhandle, $query);
?>
However if this was being done in MySQL I would be tempted to just have the nation as a unique key on the database and add ON DUPLICATE KEY SET prize=prize + VALUES(prize) to the end of the insert query.
You could write really complicated php code to do this. Or, you could change your strategy. First, let me point out that you can just use load data infile to read the data from a file.
The new strategy is to read the data into a staging table and then copy it to the final table. Basically:
read data into test_staging table (using php or `load data infile`)
insert into test(nation, prize)
select nation, sum(prize)
from test_staging
group by nation;
drop table test_staging;
So if you need it in PHP, I would suggest using a named array like this:
$insertLines = array();
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
insertLines[$nation] += $prize;
}
foreach($insertLines as $lineNation => $linePrice ) {
// The creation of the insert into the database goes here.
}
And please check the lenghts.
I think the plazer is in 14 to 15 ?
$player = trim(substr($line, 13, 2));
Am trying to display a string from my database where the first character is between 0 to 9 i tried it but still did not work below is my code help me with it thanks.
if(isset($_REQUEST['num'])){ $num = explode('-',$_REQUEST['num']);
$query1 = "SELECT usercode FROM user WHERE code like '".$num."%'" ORDER BY id DESC ";
$result1 = mysql_query ($query1) or die('query error');
while( $line1 = mysql_fetch_assoc($result1)){
echo $line1[usercode];
}
#
Your code is currently searching your database for Array since you are explode()'ing the $_REQUEST['num'], which returns an array.
You may want to create a range of numbers from your $num and then do multiple LIKE's or maybe try with a REGEXP.
Use the REGEXP function in MySQL to match code to ^[0-9] which means: "the first letter must be between 0 and 9" and in ASCII, they happen to be the numbers between 0 and 9.
This will do what you want:
<?php
if (isset($_REQUEST['num'])) {
$num = explode('-', $_REQUEST['num']);
$query1 = "SELECT usercode FROM user WHERE code REGEXP '^[" . $num[0] . "-" . $num[1] . "]' ORDER BY id DESC";
$result1 = mysql_query ($query1) or die('query error');
while ($line1 = mysql_fetch_assoc($result1)) {
echo $line1['usercode'];
}
}
?>
#
cOle2 is also right about the explode function. It returns an array, the elements of which are the input string tokenized by some delimiter. In your case, $_REQUEST['num'] based on a delimiter -.