generate 100 10-digit random numbers and save to database - php

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();
?>

Related

Using Limit in SQL according to row_count

I want to fetch number of rows with highest number of multiple of 20, Like if my table have 148 rows then limit should be 140 leaving the latest 8 entry behind, or if my table have 170 rows then limit will be 160. What will be the query in this case.
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password,
$db_name);
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$number= $_POST['number'];
$sql1 = "SELECT * FROM abc_table LIMIT WHAT TO ENTER HERE ";
As far as I know, what follows LIMIT has to be an integer literal. LIMIT won't even take something like 6/2, which would evaluate to an integer literal. I recommend just reading in the entire table, and then only processing how many rows you need in PHP.
$row_cnt = $result->num_rows;
$rs_size = $row_cnt - ($row_cnt % 20);
while ($rs_size > 0 && $row = mysqli_fetch_assoc($result)) {
// process a row
--$rs_size;
}
The above while loop should exit after reading the greatest number of multiples of 20 available. This approach is not too wasteful, since at most you would be reading in 19 extra rows from MySQL which you would end up not using.
You can use variables for this:
select t.*
from (select t.*, (#rn := #rn + 1) as rn
from t cross join
(select #rn := 0) params
order by ?
) t
where rn <= floor(rn / 20) * 20;
The ? is for the column used to specify the ordering, presumably something like id asc.
In MySQL 8+, you would use window functions:
select t.*
from (select t.*,
row_number() over (order by ?) as seqnum,
count(*) over () as cnt
from t
) t
where seqnum <= floor(cnt / 20) * 20;

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.

MySQL selecting random rows with one unique row within one query

Is it possible to select x random rows from a table, where one of the rows have to be a special row (thereby with a special field value) within one query?
Basically what I'm trying to create is a Guessing Game, where you have x amount of questions, with x amount of possible (checkbox selectable) answers!
This is how I select the answers currently... With 2 query's
$answers = 4; // This is the max amount of answers
// Just for testing the question_id is manually set
$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` != 1 ORDER BY RAND() LIMIT " . ($answers - 1) . "";
$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` = 1 LIMIT 1";
The "question_id" tells which question we are talking about, and the "correct" just tells if that field is the correct answer
So is it possible to select x random rows from a table, where one of the rows have to be "the correct one", within one query?
may be use UNION ?
$answers = 4;
$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` != 1 ORDER BY RAND() LIMIT " . ($answers - 1) . "";
$query .= " UNION ";
$query .= "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` = 1 LIMIT 1";
With one single query, you will be able to get the desired result
http://dev.mysql.com/doc/refman/5.0/en/union.html
$query = "SELECT * FROM answers WHERE ... whatever ... AND `question_id` IN (5, 9, 12, 16, 2)
So, you first find the number of rows and then put the correct answer's ID in to the WHERE IN statement. Because you know the one you want, you can just surround it with random IDs from the table and then render them in a random fashion.

loop on inserting data in mysql

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

mysql + php: Selecting multiple random results

I've been looking for this for a while but with no success.
I am trying to implement a recomendation bar, for example like in youtube, when you are seeing a video it shows the list or recommended videos on the right.
At this moment I am using this method:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `$tablename` ");
$offset_row = mysql_fetch_object($offset_result );
$offset = $offset_row->offset;
$result_rand = mysql_query( " SELECT * FROM `$tablename` LIMIT $offset, 9 " );
This works fine, but sometimes doesn't show any result, and the problem is also that its not completely random, because it shows for example the first ID as 200, so the next result will be id 201 and then 202 and so.
I would like to know if there is a way to show this 9 randon results, for example 1º result id 500, 2º result id 10, 3º result id 788, etc etc?
Thank you
Not entirely sure this answers what you are looking for, but try:
$result_rand = mysql_query("SELECT * FROM " . $tablename . " ORDER BY RAND() LIMIT 9");
You can use php rand() function to create 5 numbers and save them in an array:
http://php.net/manual/en/function.rand.php
<?php
$rand_array = array();
for($i=1;$i<5;$i++) {
$rand_array[$i] = rand(0,500);
}
?>
and after that create a query with every int with a foreach loop and work with your data.
<?php
foreach ($rand_array as $integer) {
$q = "SELECT * from $tablename WHERE id='$integer';";
}
?>
Does this helps?
First you should use mysqli_ functions instead of mysql_ because the latter is deprecated. Second use order by rand() to get random rows:
$rand_result = mysqli_query( "SELECT * FROM $tablename ORDER BY RAND() LIMIT 9;" );
UNTESTED:
SELECT id, #rownum:=#rownum+1 AS rownum, name
FROM users u,
(SELECT #rownum:=0) r
THis will give a unique number to each row in sequence. Now if you create a temp table with 9 random numbers between 1 and count(*) of your table and JOIN those two together...
Not sure about performance but seems like it might be faster than Rand and order by since I only need 9 random numbers

Categories