loop on inserting data in mysql - php

i want to insert data through loop in mysql table but it insert only a time when loop execute where i want to insert 500 Times the same data into my table below are the codes thanks in advance
enter code here
<html>
<head>
</head>
<body>
<div>
<?php
$con=mysqli_connect("localhost","root","khan","first");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
for($i=1;$i<500;$i++)
{
$sql="INSERT INTO bio(name, fathername , address) VALUES('khan','khan','khan')";
echo "Number " . $i . "<br>";
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
</div>
</body>
</html>

This is because you insert only after the loop
Try this:
for($i=1;$i<500;$i++)
{
$sql="INSERT INTO bio(name, fathername , address) VALUES('khan','khan','khan')";
echo "Number " . $i . "<br>";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
As you can see, now the mysqli_query is inside the loop and so it will execute 500 times and not just one (notice the { } positioning.
Also try not to use die();
Use proper error handling instead of this.
for instance:
for($i = 1; $i < 500; $i++) {
//INSERT AND STUFF
if(!mysqli_query($con, $sql)) {
echo "Something went wrong. Try again.";
break;
}
}
of course you might want to return what has gone wrong. So the actual error that happened in your SQL.
Look at the Mysqli documentation for this.
If you put this in a function, you dont need to use break;. Instead you can use the return "something"; statement to return the error and quit the for-loop.
Now you will end up with:
function insertFunction() {
for(.....
//DO INSERT
if(!mysqli_query(...
return "Errormessage: "+ $mysqli->error;
}
in addition you might want to look at prepared statements for your insert and how to make sure you only do 1 insert with 500 records instead of querying the database 500 times.
This might get you started on prepared statements

Include mysqli_query inside of for scope
$con=mysqli_connect("localhost","root","khan","first");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
for($i=1;$i<500;$i++) {
$mysqli_query ="INSERT INTO bio(name, fathername , address) VALUES('khan','khan','khan')";
echo "Number " . $i . "<br>";
// <<-- you always leave a closing bracket here
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
}
mysqli_close($con);
Now you can do that on db side without any loops with the query
INSERT INTO bio(name, fathername , address)
SELECT 'khan','khan','khan'
FROM
(
select a.N + b.N * 10 + c.N * 100 + 1 n
from (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) a
, (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) b
, (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) c
) t
WHERE t.n < 501
See more on populating a table with fake data https://stackoverflow.com/a/17139749/1920232

Related

SQL UNION 2 SELECT on same table

I have 2 SELECT on the same table "contratto"; in php (and mysql) I do it as:
$sql_1=" SELECT * FROM contratto WHERE id_cliente='2' " ;
$sql_2=" SELECT * FROM contratto JOIN cliente ON contratto.id_cliente=cliente.id WHERE cliente.id_rivenditore = '2' " ;
$sql= "(" . $sql_1 . ") UNION ALL (" . $sql_2 .") ; ";
mysqli_query($connect, $sql);
while($row = mysqli_fetch_assoc($risultato_query)) { ..... }
The 2 SQL query $sql_1 and $sql_2 separately work fine.
The query $sql (union of $sql_1 and $sql_2) doesn't work, that is:
( SELECT * FROM contratto WHERE id_cliente=’2′ ) UNION ALL ( SELECT * FROM contratto JOIN cliente ON contratto.id_cliente=cliente.id WHERE cliente.id_rivenditore = ‘2’ ) ;
I get the error "mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in ..."
What is wrong?
At least one error is coming from the union. All subqueries in the union need to have the same columns, so select * is not appropriate (especially in this case).
Another error comes from PHP, because you are not checking for errors from SQL. If you did, you would see the error message from the database.

generate 100 10-digit random numbers and save to database

This is a pretty simple function yet it keeps giving me errors. Im writing a script to generate 100 10-digit random numbers but I keep having this error: "check the manual that corresponds to your MySQL server version for the right syntax to use near 'rand(1111111111, 9999999999)' at line 1.
This is my code
<?php
$cxn = new mysqli("localhost", "CJroot", "password", "random");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
for ($i=0; $i < 100; $i++) {
$sql = "INSERT INTO random (random) VALUES 'rand(1111111111, 9999999999)'";
if(!mysqli_query($cxn,$sql)) {
die("Error: ".mysqli_error($cxn));
}
}
/* close connection */
$cxn->close();
?>
you need to concat your string like so.
$sql = "INSERT INTO random (random) VALUES '" . rand(1111111111, 9999999999) . "'";
The syntax error that MySQL is complaining about (in your SQL statement) is missing parens around the values list. This is invalid:
INSERT INTO ... VALUES 'foo'
Should be
INSERT INTO ... VALUES ( 'foo' )
^ ^
Once you get over that hump, the value enclosed in single quotes is interpreted as a string literal. In the example code, 'rand(11111,99999)' is a literal, a string of characters. It's not a reference to a function.
If we want to use the MySQL RAND() function, we could do something like this:
INSERT INTO random (random) VALUES ( FLOOR(1000000000 + RAND() * 9000000000) )
We can execute that 100 times, or, it would be more efficient to write SELECT statement that returns 100 rows, and insert 100 rows in a single insert.
Or:
INSERT INTO random (random) VALUES
( FLOOR(1000000000 + RAND() * 9000000000) )
,( FLOOR(1000000000 + RAND() * 9000000000) )
,( FLOOR(1000000000 + RAND() * 9000000000) )
, ...
,( FLOOR(1000000000 + RAND() * 9000000000) )
In terms of database performance, it is usually more efficient to run a single INSERT statement that inserts 100 rows, than it is to execute 100 individual insert statements. Processing RBAR (row by agonizing row) can be excruciatingly slow.
If there's a need for a loop, if we insert four rows at time, we need only need to go through the loop 25 times. And that's 75% fewer statements we need to execute.
We can specify the SQL text to be executed just one time, outside of the loop, and then just repeatedly execute that same SQL
$sql = "INSERT INTO random (random) VALUES"
. " ( FLOOR(1000000000 + RAND() * 9000000000) )"
. ",( FLOOR(1000000000 + RAND() * 9000000000) )"
. ",( FLOOR(1000000000 + RAND() * 9000000000) )"
. ",( FLOOR(1000000000 + RAND() * 9000000000) )";
for ($i=0; $i < 25; $i++) {
if(!mysqli_query($cxn,$sql)) {
die("Error: ".mysqli_error($cxn));
}
}
you can also do it direct with MySQL like this:
INSERT INTO random (random)
SELECT CAST( (RAND()*(9999999999-1111111111)) AS UNSIGNED) + 1111111111;
or for 100 rows:
INSERT INTO random (random)
SELECT CAST( (RAND()*(9999999999-1111111111)) AS UNSIGNED) + 1111111111 AS random FROM (
SELECT 0 AS h UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
) h
CROSS JOIN
( SELECT 0 AS l UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 ) l;
This works fine
<?php
$cxn = new mysqli("localhost", "CJroot", "password", "random");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO random (random) VALUES"
. " ( FLOOR(1000000000 + RAND() * 9000000000) )"
. ",( FLOOR(1000000000 + RAND() * 9000000000) )"
. ",( FLOOR(1000000000 + RAND() * 9000000000) )"
. ",( FLOOR(1000000000 + RAND() * 9000000000) )";
for ($i=0; $i < 25; $i++) {
if(!mysqli_query($cxn,$sql)) {
die("Error: ".mysqli_error($cxn));
}
}
$cxn->close();
?>

PHP select multiple Array tables

Is it possible to SELECT with multiple Array tables. I know it sounds confusing but here is what I have done :
First of all, I've created a form, that has two checkboxes option as follows :
<form action="something.php" method="post">
<input type="checkbox" name="store[]" value="M1">
<input type="checkbox" name="store[]" value="M2">
<input type="submit" value="Go">
</form>
Now after submitting the form, I can view which store selected by doing foreach loop:
$allstore = $_POST['store'];
foreach ($allstore as $store=>$value) {
echo $value;
}
Everything till now works as needed !
However those two values in checkboxes are considered to be table names ! Now how can I find a way to let PHP select either one or two tables based on user selection $value ?
$query = "SELECT * from **{$allstore[0]},{$allstore[1]}** WHERE .....";
As you can see {$allstore[0]},{$allstore[1]} should be created based under foreach loop. I can't seem to find a way of doing it! Can I insert a function to do it for me?
Like this : $query = "SELECT * from ((( Function Here ))) WHERE .....";
If you have a different way of doing it, Please share it.
Edit :
M1 Table
id |item_no |qty |price
1 x1 10 20
2 x2 5 22
3 x3 3 5
M2 Table
id |item_no |qty |price
1 x1 11 20
2 x9 5 30
3 x10 6 26
The output table should be
item_no | price | M1 | M2
x1 20 10 11
x2 22 5 N/A
x3 5 3 N/A
x9 30 N/A 5
x10 26 N/A 6
That's what I am aiming for. I hope it can be solved !
here's the structure for 2 tables sqlfiddle
I think you can add more tables from here.
SELECT T1.item_no,
COALESCE(M1.price,M2.price) as price,
M1.qty as M1,
M2.qty as M2
FROM
(SELECT item_no FROM M1
UNION
SELECT item_no FROM M2
)T1
LEFT JOIN M1 ON T1.item_no = M1.item_no
LEFT JOIN M2 ON T1.item_no = M2.item_no
UPDATED: I am not too familiar with PHP but I looked up some syntax and was able to dynamically generate SQL based on array of either ["M1","M2"] or ["M1"] or ["M2"]
DynamicPHPtobuildSQL
<?php
//Enter your code here, enjoy!
$allstore = ["M2"];
$item = 0;
$sqlpart1 = "";
$sqlpart2 = "";
$sqlpart3 = "";
$sqlpart4 = "";
foreach ($allstore as $store=>$value) {
$item += 1;
if ($item > 1){
$sqlpart1 .= ",";
$sqlpart2 .= ",";
$sqlpart3 .= " UNION ";
}
$sqlpart1 .= $value . ".price ";
$sqlpart2 .= $value . ".qty as " . $value . " ";
$sqlpart3 .= "SELECT item_no FROM " . $value . " ";
$sqlpart4 .= "LEFT JOIN " . $value . " ON T1.item_no=" . $value . ".item_no ";
}
$SQL = "SELECT T1.item_no,COALESCE(" . $sqlpart1 . ") as price," . $sqlpart2;
$SQL .= "FROM (" . $sqlpart3 . ")T1 " . $sqlpart4;
echo $SQL;
?>
Be careful to avoid the risk of SQL injection: compare the posted values against a closed list of existing store table names and reject any other value.
Note also that not only the FROM clause is influenced by the user's choices, but also the SELECT clause. So you have two dynamic parts in your SQL statement.
You could use this code which makes use of array_intersect, implode and array_map:
$selected_stores = $_POST['store'];
// Protect against SQL-injection by only accepting known tables:
$all_stores = array("M1", "M2", "M3");
$selected_stores = array_intersect($selected_stores, $all_stores);
// Build dynamic part of the FROM clause
$from = implode("
UNION
", array_map(function ($store) {
return "SELECT '$store' as store, item_no, price, qty FROM $store";
}, $selected_stores));
// Build dynamic part of the SELECT clause
$cols = implode(",
", array_map(function ($store) {
return "CASE store WHEN '$store' THEN qty END AS $store";
}, $selected_stores));
$sql = "
SELECT item_no,
MAX(price) as price,
$cols
FROM ( $from ) data
GROUP BY item_no
";
The SQL generated looks like this:
SELECT item_no,
MAX(price) as price,
CASE store WHEN 'M1' THEN qty END AS M1,
CASE store WHEN 'M2' THEN qty END AS M2
FROM ( SELECT 'M1' as store, item_no, price, qty FROM M1
UNION
SELECT 'M2' as store, item_no, price, qty FROM M2 ) data
GROUP BY item_no
See also this SQL fiddle.
As a side comment: I would advise to combine all store tables into one table, which would have an additional column indicating the store. This is more in line with normalised database design and will give more advantages than disadvantages in terms of searching, sorting, performance, and simplicity.

mysqli union arrange results per talbe

I'm using a mysqli union to search the database like so:
$search = security($_POST['search']);
$search_val = "%{$search}%";
$search_disp = '';
if($searchQ = $db->prepare(
"(SELECT name AS `name1` FROM `table1` WHERE name LIKE ? LIMIT 8)
UNION
(SELECT heading AS `name2` FROM `table2` WHERE heading LIKE ? LIMIT 8)
")){
if($searchQ->bind_param("ss",$search_val,$search_val)){
if($searchQ->execute()){
$searchQ->store_result();
if($searchQ->num_rows){
$searchQ->bind_result($search_result);
while($searchQ->fetch()){
$search_disp.='
<div>'.$search_result.'</div>
';
}
}
}
else{echo '$db->error' exit();}
}
else{echo '$db->error' exit();}
}
else{echo '$db->error' exit();}
echo $search_disp; exit();
What I dont know how to achieve is display a different result depending on the table it came from since I'm fetching both results as the same varialbe ($search_result), for example:
if(result from table one){
$search_disp.='
<div class="talbe1">'.$search_result.'</div>
';
}
else if(result from table two){
$search_disp.='
<div class="talbe2">'.$search_result.'</div>
';
}
Can someone please help me with that?
You can add additional row tbl to result set and then use it:
(SELECT 'table1' as tbl, name FROM `table1` WHERE name LIKE ? LIMIT 8)
UNION
(SELECT 'table2' as tbl, heading AS name FROM `table2` WHERE heading LIKE ? LIMIT 8)

how to combine more than one mysql query into single query

i have 3 different queries like below:
$query = "select category_id,category_name from category";
$result = $this->Dbmodel->customQueryResult($query);
$query = "select location,location_name from sub_category";
$result_one = $this->Dbmodel->customQueryResult($query);
$query = "select category_date,category_month from other_category";
$result_two = $this->Dbmodel->customQueryResult($query);
here i am calling mysql server 3 times to execute my query and getting the result thereby..
now i am thinking how can i reduce mysql call so that all these 3 query gets executed in one single query so making only 1 call to mysql server and displaying all different results to user using php
how can i do this.. any help or suggestion would be a great help.. thanks in advance
What you've described is an SQL UNION.
Below is an example query you could use to achieve your goal:
SELECT category_id,category_name FROM category
UNION
SELECT location,location_name FROM sub_category
UNION
SELECT category_date,category_month FROM other_category
Example usage:
$query = 'SELECT category_id, category_name FROM category
UNION
SELECT location, location_name FROM sub_category
UNION
SELECT category_date, category_month FROM other_category';
$result = $this->Dbmodel->customQueryResult($query);
echo 'CategoryID: ' . $result['category_id'] . '<br />';
echo 'Category Name: ' . $result['category_name'] . '<br />';
echo 'Location: ' . $result['location'] . '<br />';
echo 'Location Name: ' . $result['location_name'] . '<br />';
echo 'Category Date: ' . $result['category_date'] . '<br />';
echo 'Category Month: ' . $result['category_month'];
Keep in mind, in case you need to select fields with identical names from different tables to use SQL aliases. An example of an alias:
SELECT category_id AS `catID` FROM category
Instead of $result['category_id'], you would use $result['catID'] instead.
As you are saying none of the tables are related, you have to fetch 3 queries.
You shouldn't combine queries, if there is no any relation. Otherwise it will give you ambiguous data.
We use sub-queries, joins when there is some relation to minimize queries.
Anyways you can get 3 queries result, if 1st, 2nd column have same data type and you can identify from 3rd column it's table name.
SELECT category_id,category_name, 'category' FROM category
UNION
SELECT location,location_name, 'sub_category' FROM sub_category
UNION
SELECT category_date,category_month, 'other_category' FROM other_category
THIS WILL BE EXACT QUERY
$query = "select category.category_id,category.category_name, sub_category.location,sub_category.location_name,other_category.category_date,other_category.category_month from category,sub_category,other_category";
You can use joint properties something like that.
$query = "select * from category, sub_category, other_category";
Note: on *, you can read this question MySQL - specific columns on join?
If the tables are related you could use joins. If that not the case you could use mysql UNION
It would be something like ...
$query = "select category_id,category_name from category UNION select location,location_name from sub_category UNION select category_date,category_month from other_category";
If all 3 Query have same data then we can Combine all 3 queries, Otherwise it would be not useful.
The Other way, Would be as Follows
Select c.category_id, c.category_name,
l.location,l.location_name,
o.category_date,o.category_month
from category C,
sub_category l,
other_category o
But Above would does get the Meaningful Data.

Categories