I have a very large data (not a file) to insert into a students' database. It will be very difficult to type every inch of it, loop and insert. However, it follows a specific pattern and it's in a range of specific numbers.
Below is an example of what I am talking about.
Student's Reference Numbers
Sample range: APS00001 - APS02000
The first three characters are constant. but the rest are not. The data has to be inserted based on the given range.
<?php mysqli_query($conn,"INSERT INTO table (reference) VALUES('each of the data in the sample range')"); ?>
So I could generate the sequence using this code
<?php
$array_items = array();
for ($i=0; $i <= 2000; $i++) {
$array_items[] .= $i;
}
print_r($array_items); // prints the sequence
?>
Here is an SQL solution to your INSERT problem.
Run this to loop from 1 to 2000. It generates APS0001, padding the number as it goes.
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_data $$
CREATE PROCEDURE insert_data ()
BEGIN
DECLARE count INT DEFAULT 1;
WHILE count <= 2000 DO
INSERT INTO `tbl1`(`col3`) VALUES(CONCAT("APS",LPAD(count, 4, '0')));
SET count = count + 1;
END WHILE;
END $$
DELIMITER ;
CALL insert_data();
Since the original post was updated, here is a PHP solution:
<?php
// add $conn info
for ($i = 1; $i <= 2000; $i++) {
$insdata = "APS" . str_pad($i, 5, "0", STR_PAD_LEFT);
mysqli_query($conn,"INSERT INTO table (reference) VALUES('$insdata')");
}
?>
You should use prepared statement with parameter binding. To pad the string to a given length use str_pad(). You can prepend the APS string either in PHP or in SQL using CONCAT().
$sql = "INSERT INTO table (reference) VALUES(CONCAT('APS', ?))";
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $value_to_be_inserted);
$array_items = array();
for ($i = 1; $i < 20; $i++) {
$array_items[] .= +$i;
$value_to_be_inserted = str_pad($i, 5, '0', STR_PAD_LEFT);
$stmt->execute();
}
Don't prepare in the loop. Only execute inside the loop.
Related
<?php
$list = ['a', 'b', 'c'];
$count = [1, 3, 5];
function stringFormatter($c, $i) {
return "Char is $c & Int is $i";
}
for ($i = 0; i < $list; $i++) {
for ($j = 0; $j < $count; $j++) {
$string = stringFormatter($list[$i], $count[$j]);
print $string;
}
}
?>
This is sample code that I have rewritten to demonstrate an issue I'm having with a program where I want to assign a formatted string, with the right combination of char and int, to be able to execute an SQL statement, using said string. Ideal scenario is getting a string that has the combination of both char and int at that position in their respective lists. E.g. "Char is a & Int is 1". This doesn't currently compile and when I plug it into "Online PHP Sandbox" I get the error message: "Internal Server Error [500]." Any advice on how I could get this to work, or even alternative suggestions are welcome! Thanks in advance!
for ($i = 0; i < $list; $i++) {
for ($j = 0; $j < $count; $j++) {
There are a few syntax errors here - watch out for a missing $ (look at the i inside the outer loop). You probably mean something like $i<count($list) using the built in count function. Similarly in the inner loop you are referencing the $count array with $j<$count - do you mean $j<count($count) or are you using the outer array as in index for the inner element i.e. $j < $count[$i].
On a more general note there are a collection of functions built into php to better handle passing of values into mysql (etc) - you should probably be looking at using those - search on "sanitising" with php and mysqli.
I want to merge cells dynamically based on count using PHPEXCEl.
For example:
if $count = 2;
I want to merge two cells as given below,
$objPHPExcel->getActiveSheet()->mergeCells('A1:B1');
similarly, if $count = 4;
$objPHPExcel->getActiveSheet()->mergeCells('C1:F1');
similarly, if $count = 5;
$objPHPExcel->getActiveSheet()->mergeCells('G1:K1');
I want to get this logic in a loop.
I tried the below logic, which doesn't work
$count = ew_Execute("SELECT COUNT(*) FROM ems_defects_codes WHERE DEF_CODE = '$def_code'");
$start_letter = A;
$rowno = 1;
for ($i = 0; $i < $count ; $i++) {
$objPHPExcel->getActiveSheet()->mergeCells($start_letter.$rowno.':'.$i.$rowno);
}
Any help will be much appreciated.Thanks..!!
You need to get column range string value for the inputs - start_letter, row_number and count. Once the column range is available, same can be used in the PHPExcel mergeCells function. Here is example code to get column range:
function getColRange($start_letter, $row_number, $count) {
$alphabets = range('A', 'Z');
$start_idx = array_search(
$start_letter,
$alphabets
);
return sprintf(
"%s%s:%s%s",
$start_letter,
$row_number,
$alphabets[$start_idx + $count],
$row_number
);
}
print getColRange('A', 1, 2) . PHP_EOL;
print getColRange('C', 1, 4) . PHP_EOL;
print getColRange('G', 1, 4) . PHP_EOL;
Output
A1:C1
C1:G1
G1:K1
Further you can use this new function with your code to do actual merge. You can choose to call this function or in a loop.
$sheet = $objPHPExcel->getActiveSheet();
$sheet->mergeCells(
getColRange(
$start_letter,
$row_number,
$count
)
);
The problem is that your $i inside of your loop is always going to be an integer; you need to convert that integer to the corresponding index of the alphabet, by creating an alphabetic array. This can be done with a simple range('A', 'Z').
You also need to wrap the A in $start_letter in apostrophes (as 'A'), and now that the range has been created, you can simply use the index of the alphabet for that:$start_letter = 0 (later becoming 'A' with $alphabet[$start_letter]).
Then you'll need to add the starting letter to the count for in order to get the ending cell in mergeCells(). Your starting cell now becomes $alphabet[$start_letter] . $rowno, and your ending cell now becomes ($alphabet[$start_letter] + $alphabet[$i]) . $rowno.
This can be seen in the following:
$count = ew_Execute("SELECT COUNT(*) FROM ems_defects_codes WHERE DEF_CODE = '$def_code'");
$alphabet = range('A', 'Z');
$start_letter = 0;
$rowno = 1;
for ($i = 0; $i < $count; $i++) {
$objPHPExcel->getActiveSheet()->mergeCells($alphabet[$start_letter] . $rowno . ':' . ($alphabet[$start_letter] + $alphabet[$i]) . $rowno);
}
I am trying to implement a quick search bar to search a table populated by an SQL database. The search will not search the table, but will generate SQL statements and search the database. I need to implement a search function using PHP that will use flags to stop the search. This is my code so far:
//THIS CODE WILL EXECUTE WHEN THE SEARCH BUTTON IS PRESSED
if($_REQUEST['btnsearch']){
if(isset($_POST['quicksearch']) and !empty($quicksearch)){
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name ='alerts_table'
AND column_name IN('name', 'year','make','model','alert','date')";
$retvalues = mysqli_query($conn, $sql);
$data = array();
//LOOP POPULATES THE ARRAY WITH THE CURRENT COLUMN NAMES.
for($counter = 0; $counter <= $row=mysqli_fetch_array($retvalues, MYSQL_ASSOC); $counter++){
$string = $row["column_name"];
$data[$counter] = $string;
}
$length = count($data);
$flag = 1;
while($flag == 1){
for($x = 0; $x <= $length - 1; $x++){
$sql3="SELECT * FROM alerts_table WHERE $data[$x] = $quicksearch";
$retvalues2=mysqli_query($conn, $sql3);
if(!empty($retvalues2))
{
//POPULATE THE TABLE WITH RESULTS HERE !!!!!!!!!
$flag = -1; ///HOW CAN I BREAK THE LOOP???
}
}
}
}else{
From the PHP break documentation:
(PHP 4, PHP 5, PHP 7)
break ends execution of the current for, foreach, while, do-while or
switch structure.
break accepts an optional numeric argument which tells it how many
nested enclosing structures are to be broken out of. The default value
is 1, only the immediate enclosing structure is broken out of.
In your case you have two loops; a while loop and an inner for loop. You can set your flag in your inner loop to a value that will stop the while loop, and then use a break to stop the for loop.
$flag = 1;
while($flag == 1){
for($x = 0; $x <= $length - 1; $x++){
// ...
if(!empty($retvalues2))
{
$flag = -1; // set while condition to false
break; // break out of for loop
}
}
// execution continues here after break
// end of while body, start next loop iteration
// $flag == 1 => false, and the while loop will end
}
I am trying to generate an id with fixed alphanumeric part and a varying 3 digit numeric part.
That is, the id will look like:
LAB-SER-420316-1415-000
LAB-SER-420316-1415-001
...
LAB-SER-420316-1415-010
LAB-SER-420316-1415-020
...
LAB-SER-420316-1415-110
LAB-SER-420316-1415-210
.....
My task is to generate this id's only once, that is repeating id has to be avoided. Also once the page is loaded, it should generate single id.This is like giving a bill number or something like that. I've created a function to generate this string upto a limit. But I need it to generate everytime the page is loaded.
Code:
<?php
function generatebillno()
{
$saved="LAB-SER-420316-1415-";
for($count = 0; $count <= 999; $count++)
{
$var= str_pad($count, 3, '0', STR_PAD_LEFT);
return $saved.$var;
}
}
echo generatebillno();
?>
Can anyone help me to do this. I am stuck here..
try this -
//fetch the max id (the last digit as number)
$sql = $mysqli->query('select max(cast(substring(demo_field, 21) as unsigned)) as digit,
demo_field from demo');
$res = $sql->fetch_assoc();
//check for empty valyues
if (empty($res['demo_field'])) {
$str = "LAB-SER-420316-1415";
$res['digit'] = 0;
} else {
$str = substr($res['demo_field'], 0, 19);
}
$dig = $res['digit'] + 1;
//add padding if needed
$dig= str_pad($dig, 3, '0', STR_PAD_LEFT);
$newStr = $str.'-'.$dig;
var_dump($newStr);
I am trying the use refine tools for a search on my website. The bit i'm stuck with is search by start letter. For example i could use a wildcard '%X%' but his would return anything that contained the letter 'x'.
I read on few sites that SUBSTRING can be used in mysql queries
http://dev.mysql.com/
http://www.kirupa.com/
https://stackoverflow.com/questions/6302027
This is what I have so far but returns nothing. There is data in the database that should return with the query.
public function refineUsersFollowers($user_id,$q){
if($this->databaseConnection()){
// get the users followers
$state = array(1,2);
$stmt = $this->db_connection->prepare("SELECT * FROM friends WHERE id_2 = :1 AND Friend_Request_State = :2 OR id_2 = :3 AND Friend_Request_State = :4");
$stmt->bindParam(':1', $user_id);
$stmt->bindParam(':2', $state[0]);
$stmt->bindParam(':3', $user_id);
$stmt->bindParam(':4', $state[1]);
$stmt->execute();
// format the SQL OR statements
$sql = '';
$ids = [];
while($rows = $stmt->fetch(\PDO::FETCH_ASSOC)){
array_push($ids,$rows['id_1']);
}
for($x = 0; $x < count($ids); $x++){
if(count($ids) == 1){
//if there is one result
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x;
}else if($x == (count($ids) - 1)){
// last entry
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x;
}else{
//continue loop
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x." OR";
}
}
$stmt = $this->db_connection->prepare("SELECT * FROM account WHERE ".$sql);
for($x = 0; $x < count($ids); $x++){
$stmt->bindParam(':'.$x,$ids[$x]);
$insert = $x.$x.'';
$stmt->bindParam(':'.$insert,$q);
}
$stmt->execute();
$results = $stmt->fetch(\PDO::FETCH_ASSOC);
print_r($results);
// check for followers that start with letter
}
}
The first part of the function is fine, this gets an array of id's which is then placed together as an SQL string. Is the SQL not returning results because SUBSTRING is not supported in this way?
If so is there a way of producing a query like this or would it be easier to pull every result from the database then check them in a different function?
You have two issues with this expression:
SUBSTRING('first_name', 0, 1) = :".$x.$x;
First, substr() in SQL (in general) starts counting with 1 and not 0. So, the first argument should be 1.
Second, you have the first argument in single quotes. So, at best, this would return the letter 'f'. Here is a simple rule: Only use single quotes for string and date constants. Never use single quotes to refer to column names.
There are several way to write what you want. Here are three:
SUBSTRING(first_name, 1, 1) = $x
LEFT(first_name, 1) = $x
first_name like '$x%'
You query can be greatly simplified with the LIKE operator. This:
"AND SUBSTRING('first_name',0,1) = :".$x.$x;
can become this:
"AND first_name LIKE '".$x.$x."%'";
I'm not sure what the $x.$x is for, so I just left it in for illustrative purposes.