Numbers and calculations in php/sql - php

ok im new on the scene with php and sql, i read the basics and was able to produce a DB driven shoutbox.
This is my website http://www.teamdelta.byethost12.com/
What i want to do next im not sure what i should be using java? php? sql? i have no idea...
but i assume php and sql if sql can do what i think it can..
What i want to do next is to A extract data from data at certain positions for example
data in the format "DAB:CD:EF:GH" eg "D03:57:16:23" to be turned into AB, DF, CE. Eg "3","76","51".
then i want to store these Numbers (Not VARCHARS) in the database.
that is part 1.
the sceond part that i want to make sure is possible before i put to much effort in is to do calculations on all the entries in the database with respect to a 3rd peice of data and display all the entries in a decending ordered list ordered by the output of the calculation..
i think calculations can be added to querys...but as i said im new and the tutorial i read only coved reading values out of the db..
and just if it helps to clarify what im trying to do even though this is not part of the question... here is what im trying to do
* set up a database and entry system that records the player name, base name, location,econ, and comment and stored this as a entry in the database..(i have done this)
*on entry i wish to extract numeric values(AB,DF,CE) from a text string(location) (dont know how)
*then i wish to display the list(i have done this)
*a new column should be added on display containing the resuly of a calculation involving the numberic values from each entry with a global value that is entered on page(dont know how)
*then the list should be sorted in decending order of the output of the calculation.
*lastly i wish to be able to remove items from the list with a click.
thats all :) ,, seeking part advice and guidence
here is the page its php but i renamed it as text so its readble.
cant past is as code as it has escape chars in it
http://www.teamdelta.byethost12.com/trade/postroute3.txt
currently trying to use
$values = array();
$string = $location;
$values[0]= $string[1].$string[2];
$values[1]= $string[5].$string[8];
$values[2]= $string[4].$string[7];
$x = intval($values[1], 10);
$y = intval($values[2], 10);
$g = intval($values[0], 10);
print_r($x);
echo(' : '); print_r($y); echo(' : ');
print_r($g);

ok.. for the first part.
$values = array();
$values = split(":", 'DAB:CD:EF:GH');
$int_values = array();
foreach($values as $v) {
$int_values[] = intval($v, 10);
}
// values in base 10
print_r($int_values);

Related

Replacing content of block after generating clones using cloneBlock - PHPWord

Please can somebody be so kind to show me the syntax for using cloneblock in phpword.
So Ive got data in a MySQL DB, and for the single rows that I need to import into my word doc via phpword it works fine....to run my query and search and replace with template processor. BUT, now I want to insert multiple rows into my word document. I've researched and found that the cloneblock method is the answer. However I cannot get it working....currently my code runs but it doesn't seem to get to the second row.
I actually dnt get any error messages. My code executes fine...but the end display word file doesn't display fine....and if you see my code I got an echo statement...which echo's out in my browser exactly what I want "damaged" &"good", (as an example given of one of the row data) but that data doesn't get pulled into my word doc like that...it duplicates "damaged" , "damaged". .
$group_key=1;
do {   
//loop to increase my uuid  - ($repeatgroup')
$repeatgroup = $id."/"."trailer_repeat_group"."[".$group_key."]";
// query string
$trailer_repeat_grouping = mysqli_query($connect, "SELECT * FROM trailer_repeat_group LEFT JOIN main on trailer_repeat_group.PARENT_KEY = main.metainstanceID WHERE trailer_repeat_group.KEY_id = '$repeatgroup'");
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
while ($row1 = mysqli_fetch_array($trailer_repeat_grouping)) {   
//this echo below I am using to test exactly what happends – independent of
//PHPword/templateprocessor
echo $rttc =  $row1['right_trailer_tyre_condition'];
//inserting  / searching / inserting values
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
}
// ending of loop / checking loop
$group_key++;
} while ($group_key <= $trailer_count);
I've done investigation and found the solution.
You're cloning same blocks N times:
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
and then by doing fetch You're trying to replace right_trailer_tyre_condition with some value:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
Issue is that You're replacing all placeholders.
But in fact You need to replace them one by one with different values.
Solution is to define 3rd argument that means count of items to replace.
Simply change it to be:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc, 1);

Echo repeated variables loop php

you see, I have these variables that are set within a While, I'm using MySQL also, What I want to do is to sort of "Group" those variables into one, and then the rest of the variables that are not repeated, i want to assign them "Display:none" So , look at this image:
Now, as you can see there is two duplicate dates, but the values are different, so in this case (Take in mind that I only want to group these "Recibos" but dont worry about it) you can see in the first row it has a different date, and has no repeated dates, while the last two of "Recibos" is sort of duplicated
Basically what I want to do is to group the two last "Recibos" (The duplicate dates), only one of the same date has to appear, and the rest of them, are gonna be shown when the TR is hover
Though , I only want a simple version of what I want, it can be some sort of testing, as you can see in this image, i've been trying for weeks and still didnt get anything, I hope you can help me! thanks in advance
I have made this code, which is the one in the image above:
Inside the while:
$acumulado-=$monto;
if(($fila>=$mostrar_de_aca_en_adelante && $detalles=='minimo') || ($detalles=='maximos')){
$conteo++;
$string_fecha[$conteo] = $fecha_operacion;
$string_fecha_tmp[$conteo] = $fecha_operacion;
$recibo_id_cliente[$conteo]=$id_cliente;
$recibo_monto[$conteo]=$monto;
$recibo_saldo_total[$conteo]=$saldo_total;
$recibo_detalle_movimiento[$conteo]=$datos_detalles['detalle_movimiento'];
$recibo_recibo[$conteo]=$recibo[0];
$recibo_verificado[$conteo]=$datos_detalles['verificado'];
$recibo_acumulado[$conteo]=$acumulado;
$label = $monto;
}
Outside the while:
echo "<br><br><br>";
for($i = 1; $i <= $conteo; $i++){
if($string_fecha[$i] == $string_fecha_tmp[($i + 1)]){
$label += $recibo_monto[$i];
$string_imprime_tmp .= "<br>[Repetido]".$string_fecha[$i]."(".$label.")";
}
}
echo $string_imprime_tmp;
var_dump($string_fecha);
By the way: I know this can be done in MySQL, but it can only be done in php i'm limited to php.

Mysql INSERT SET type

Sorry for my English but it is not my native language.
I have created a user interface to insert data to MySQL. Everything except one thing is ok but when I want to read data from multiple checkboxes and write them to SET type in MySQL it just doesn't work. I have tried to find the answer but after 4 hours I can't find it or I don't understand it.
http://jyxo.info/uploads/21/21b104df77f6ca723bb708d8d0549af5430e8e91.jpg
dobaVyskytu is SET type and there are in with month you can find mushroom(my tema is online atlas of mushrooms)
in user interfacei have 12 checkbox for 12 month.
http://jyxo.info/uploads/FD/fd548760b155307dfa677ada7c4be4996abf7b93.png
In dobavyskytu i need to have multiple select and that is reason why i use $doba +=
if(isset($_POST["Leden"]))
{
$doba += "Leden";
}
if(isset($_POST["Únor"]))
{
$doba += "Únor";
}
if(isset($_POST["Březen"]))
{
$doba += "Březen";
}
Db::query("INSERT INTO houby(nazev,dobaVyskytu,mistoVyskytu,popis,jedovatost,img)VALUES(?,?,?,?,?,?)",$nazev,$doba,$misto,$popis,$jedovatost,$foto);
Thank you all for reading and for help because it works now.
For strings in PHP, it uses . as concatanation not +, so
$doba .= "Leden";
Edit:
For a better way of doing this, you should try something like...
$options = [];
if(isset($_POST["Leden"]))
{
$options[] = "Leden";
}
if(isset($_POST["Únor"]))
{
$options[] = "Únor";
}
...
$doba = implode(',', $options);
As this will give you something like Leden,Únor
My hypotheses are:
$doba is the variable you want to insert in your SET type column (I translated and it seems the values you put as example in your question is Slovak for "January", "February", "March" -- I suppose there could be more).
I suppose that your SET type column is "dobaVyskytu" and that you created it correctly in MySQL by including all the possible values in the column definition.
(Your question update seem to confirm my hypotheses!)
First, when you want to insert multiple values in a SET type column in MySQL, the string value has to be separated with commas.
With the code I see, you can end up with that string "LedenÚnorBřezen" (I suppose you use += for string concatenation, but you should really use .= like Nigel Ren mentionned). You really want to end up with a string like "Leden,Únor,Březen" if all the 3 values you show are checked in your form.
See here for how to handle SET type in MySQL:
https://dev.mysql.com/doc/refman/5.7/en/set.html
Since you do not know if you will end up with 0 or multiple values for that column, I would suggest to make $doba an array.
$doba = array(); // depending on your PHP version, you can also write $doba = [];
After, you can add your values this way (the syntax $array[] = 'value' will apprend a value to the array):
$doba[] = "Leden";
$doba[] = "Únor";
$doba[] = "Březen";
Then, before inserting it, you can convert the array to a string with the values separated by commas that way:
$csvDoba = implode(',', $doba);
Then use $csvDoba instead of $doba in your Db::query() line.
After you get this working, here are more things you can look for to improve your code:
You can also take advantage PHP magic by naming your form checkbox with a special name to avoid repeating yourself.
For example, you can name all your checkboxes with the name "doba[]", and if (isset($_POST["doba"]), it will already be an array with all the checked values! But beware, if no value is checked, it won't be set. That way, you will avoid doing an if condition for each of your checkbox.
You can do something like this in your code to retrieve the value:
$doba = isset($_POST['doba']) ? (array) $_POST['doba'] : array();
What this do?
If any checkboxes named "doba[]" is checked, then you will retrieve them and make sure the value you retrieve is of type array, the "(array)" part for the value to be an array even if it was not (e.g., an error or someone trying to hack your form). Else you will return an empty array (as no choices has been put).
If you are not familar with this syntax, do a searcch for "ternary operator".
You will of course want to do some validation of your values if not already done
You might look to put the values in another table instead of using the "SET type", but that is up to you and at this stade you probably still have a couple stuff to learn, so I don't want to flood you with too much info. ;-)

Opencart 2.0.1.1 - product/search.php, cant figure out where to add extra functionality

I think the correct file to alter is catalog/controller/product/search.php to add extra functionality to search. Basically I wanted to grab a specific attribute that product have and run the array of results through. So I have the next difficulties:
$search = $someInput; // Where do i get search input?
$arraySearch = compact($search); // Compact it to array
$resultsArray = SELECT desired_attribute FROM product_table; // Insert my desired query, where do I do that? Is there some quick way, like get->?
$filteredResult = preg_replace("/[^0-9]/","", $resultsArray->desired_attribute'); // Filter it to numbers only.
array_intersect($arraySearch, $filteredResult); // find product based on this intersect.
May I have some ideas? It's just Opencart is really horribly documented. This is very easy with frameworks.

Print data from a DB grouped under the starting letter using PHP?

I'm trying to set up a for loop to print all data from a database table that starts with a certain letter. For example, let's say from all the usernames in the database, I only want to print every username starting with the letter "b". My end result I want to achieve is something along the lines of this:
A
adam
angel
apple
B
ball
bear
blue
C
car
cell
chris
#
0wen
1uis
3than
.,_
.apple.
,car,
_jeff_
I want to be able to print all usernames under the corresponding character in which they start with. I have the starting characters under heading tags, so all I really need is to print the usernames under them. I figured running a simple for loop under each heading tag that filters that data would do the trick, but I for the life of me can't figure out how to go about doing it. This my code so far (I know this will print every user in the table):
require_once 'important/connect.php';
$query = $link->prepare('select distinct usr from info order by usr');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_OBJ);
foreach ($users as $user)
{
print "<center>{$user->usr}</center>";
}
This code above is merely to show what I'm working with. I'm shooting to keep each username to print as a url as well, so when their username is clicked, it will display more information in a seperate pop up window, however I already have that working. Anyway, how would I implement this or is the way I wanna go about it not possible?
For the loop you can use this PHP syntax:
foreach(range('A','Z') as $letter) {
//your own code
}
range will make you iterate through the letters as you do usually with foreach.
The point about your question is about performance.
If you have a small amount of data to return you can return the whole array and then search with php functions to manipulate arrays only the items that begins with $letter.
If you have many items it is better (IMHO) to run a query for each letter using mysql instruction LIKE (cause this will improve performance):
"SELECT usr FROM info WHERE usr LIKE '$letter%' ORDER BY usr GROUP BY usr"
LIKE will match only those usr that will start with $letter and will have anything else following. % is the wildcard to be used.
Also note that in the query I have used GROUP BY usr instead of SELECT DISTINCT usr to get the same result as this is the right way to get an unique list of users.
As Lelio Faieta pointed out, looping through the user list over and over again might be bad for performance. However, querying the database over and over again might also be bad.
So I would suggest getting the users just once, and getting them in the right order:
SELECT usr FROM info ORDER BY usr GROUP BY usr
Then loop through them, and keep track of what starting letter you're on:
$oldLetter = '';
$newLetter = '';
foreach ($users as $user)
{
$newLetter = strtoupper(substr($user->usr, 0, 1));
if($oldLetter != $newLetter)
{
//We are on a new letter.
//Print a heading for all letters between the old one and the new one.
foreach(range(++$oldLetter, $newLetter) as $letter)
print '<h2>' . $letter . '</h2>';
$oldLetter = $newLetter;
}
//Print the user, as before.
print "<center>{$user->usr}</center>";
}
This will not take care of the last group (titled # in your example) for you. To do that, you will need to check whether the first character is a letter in the SQL and sort on that somehow.
Please note that this code is not copy-paste-ready, you will need to work some on it. For instance if the old letter is Z there might be some problems. I have not tested this, so you should before you put it into production.
Pseudo code for a nasty solution:
$alphabetArray = array("A","B", etc);
foreach($alphabetArray as $letter) {
echo '<h2>'.$letter.'</h2>';
$sql = "SELECT * FROM `usertable` WHERE `username` = '".$letter."%' ORDER BY `username` ASC;"
// execute sql, loop through and output results
}

Categories