how to insert random value in to database mysql ?
Ok, when i load this code i will have random number format like this
5,3,1,6,4,
and i want to insert 5,3,1,6,4, into database mysql ( 1 row 1 column) , how can i do ?
<?
$cards = array();
for ($i = 0; $i < 5; $i++)
{
$card = mt_rand(1, 6);
if(!in_array($card, $cards))
{
$cards[$i] = $card;
}
else
{
$i--;
}
}
foreach ($cards as $cards)
{
echo $cards.",";
}
?>
How does it differ from inserting non-random values ?
mysqli_query($link, "INSERT INTO yourtable (id, cards) VALUES (NULL, '$cards')");
Or something similar.
Pure (My)SQL solution:
INSERT INTO test( x, y )
SELECT 10*rand(),
10*rand()
FROM information_schema.columns
LIMIT 10;
Demo: http://www.sqlfiddle.com/#!2/be6e5/2
The easiest way to do what you describe would be as #Martin answered.
However this will probably screw you up later. Ideally you don't want to store a list in a RDBMS field; it defeats the whole purpose of having a database.
If you make a table like
ID, cardPosition, cardID
You can do this:
$insert = $db->prepare("INSERT INTO cardpositions (cardPosition, cardID) VALUES (:cardPosition, :cardID)");
foreach ($cards as $cardPosition=>$card)
{
$insert->execute(array(':cardPosition' => $cardPosition, ':cardID' => $card));
}
OR
The wrong way to do this, but the one you seem to want is:
$cardlist = implode(",",$cards); //now you have a comma separated list without the trailing comma
then you do this if PDO:
$insert = $db->prepare("INSERT INTO cardpositions (cardlist) VALUES (:cardlist)");
$insert->execute(array(':cardlist' => $cardlist));
or this if mysqli:
mysqli_query($link, "INSERT INTO yourtable (cardlist) VALUES ('$cardlist')");
Related
My Code is given below :
$trend=5,6,7;
$variableAry=explode(",",$trend);
foreach($variableAry as $var)
{
$sql="insert into trending_lawyer(id,lawyers_id)values('','$var')";
$query=mysql_query($sql);
}
Please suggest me to what to do/modify in this code to insert values in database.
What about doing it something like:
$trend='5,6,7';
$variableAry=explode(",",$trend);
foreach($variableAry as $var)
{
$sql="insert into trending_lawyer(id,lawyers_id)values('','$var')";
$query=mysql_query($sql);
}
There are other ways to optimize you code, but, for starters, this should work for you.
Just realized that you are trying to insert id as part of insert statement, if id is a PR and AI column, you can skip it in you insert statement, so, you code will look like:
$trend='5,6,7';
$variableAry=explode(",",$trend);
foreach($variableAry as $var)
{
$sql="insert into trending_lawyer(lawyers_id)values('$var')";
$query=mysql_query($sql);
}
$variableAry = explode(",", $trend);
$sql = "insert into trending_lawyer(id,lawyers_id)values";
for ($i = 0; $i < count($variableAry); $i++) {
$sql.="('','$variableAry[$i]'),";
}
$sql=trim($sql,',');
$query = mysql_query($sql);
Query looks like :
insert into trending_lawyer(id,lawyers_id)values('','5'),('','6'),('','7')
So, I've got a few txt files, each container around 400,000 lines.
Each line is a word, I need to add to my database, if it isn't in there already.
Currently my code for checking/adding every word is
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
if($num == '0'){
$length = strlen($word);
$timestamp = time();
#mysql_sql("INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ('{$word}', '{$length}', '{$timestamp}')");
}
and the functions being called are:
function mysql_sql($sql){
global $db;
$result = $db->query($sql);
return $result;
}
function mysql_num($result){
return $result->num_rows;
}
I'm looking for a better way to insert each word into the database.
Any ideas would be greatly appreciated.
I can think of some ways to do this.
First, if you have access to the MySQL server's file system you can use LOAD DATA INFILE to create a new table, then do an insert from that new table into your word_list table. This will most likely be your fastest option.
Second (if you don't have access to the MySQL server's file system), put a primary key or unique index on word_list.word. Then get rid of your SELECT query and use INSERT IGNORE INTO word_list .... That will allow MySQL automatically to skip the duplicate items without any need for you to do it with a query/insert operation.
Third, if your table uses an access method that handles transactions (InnoDB, not MyISAM), issue a BEGIN; statement before you start your insert loop. Then every couple of hundred rows issue COMMIT;BEGIN; . Then at the end issue COMMIT;. This will wrap your operations in multirow transactions so will speed things up a lot.
Try out this code. It will first create query with all your values and you will run query only ONCE ... Not again and again for ever row
$values = array();
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
$insert_query = "INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ";
if ($num == '0') {
$length = strlen($word);
$timestamp = time();
$values[] = "('$word', '$length', '$timestamp')";
}
$insert_query .= implode(', ', $values);
#mysql_sql($insert_query);
I have a text file to read which has around 10000 points separated by,
x1,y1
x2,y2
x3,y3
.
.
10000 times
I read them using a loop in PHP and then store in an array and then I run a loop and insert one line at a time in my database. It takes really long time. Is there any way I can insert the whole array
for ($i=0; $i<10000; $i++)
{
$sql = '
INSERT INTO `firefly`.`FreeFormPoly`
(`markedObjectID`, `order`, `x`, `y`)
VALUES
('.$markedObjectsID.', '.$order.', '.$valuesx[i].','.$valuesy[i].')';
$db->query($sql, $markedObjectsID, $order, $values[1], $values[0]);
}
Try using multiple insert statement. Generate one insert and submit the entire statement
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
SO:
$sql = 'INSERT INTO `firefly`.`FreeFormPoly` (`markedObjectID`, `order`, `x`, `y`) VALUES';
for($i=0;$i<10000;$i++) {
if($i != 0) $sql .= ',';
$sql .= '('.$markedObjectsID.', '.$order.', '.$valuesx[i].','.$valuesy[i].')';
}
$db->query($sql);
I would do something like this:
$sql = 'INSERT INTO `firefly`.`FreeFormPoly` (`markedObjectID`, `order`, `x`, `y`) VALUES';
for($i=0;$i<length;$i++) {
$sql .= '('.$markedObjectsID.', '.$order.', .$valuesx[i].','.$valuesy[i].'),';
}
$sql = substr($sql,0,-1);
$db->query($sql);
Explanation:
The syntax to enter multiple records is
INSERT INTO TABLE_NAME VALUES(VAL1, VAL2, ....), (...), (...);
In the SQL you are concatenating (val1,val2,val3), every time you execute the loop hece you will get an extra , in the last position and substr() trims it off.
More preferably I would do
$sql = 'INSERT INTO `firefly`.`FreeFormPoly` (`markedObjectID`, `order`, `x`, `y`) VALUES ';
for($i=0;$i<length;$i++) {
$sql .= '('.$markedObjectsID.', '.$order.', .$valuesx[i].','.$valuesy[i].'),';
}
$sql = substr($sql,0,-1);
$result = mysqli_query($db,$sql)
or die('Error in querying the database');
You should be able to speed it up considerably by sending BEGIN TRANSACTION before the loop and COMMIT after the loop. One time I had to insert 14,000 data points on SQLite, and it took 20 minutes, but when I put the data in as a transaction it completed in 0.3 seconds.
First off, you can use prepared statements to reduce the network overhead. Assuming PDO:
$stmt = $db->prepare('INSERT INTO mytable (foo, bar, baz) VALUES (:foo, :bar, :baz)');
for ($i = 0; $i < $length; ++$i) {
$stmt->execute(array(
':foo' => $data[$i]['foo'],
':bar' => $data[$i]['bar'],
':baz' => $data[$i]['baz'],
));
}
Second, you could wrap the whole code inside $db->beginTransaction() and $db->commit().
starting query to display result:
$at = array();
$num=array();
$i=0;
while($rw=mysql_fetch_array($r))
{
echo $rw['c_number']
$number=$rw['c_number'];
$num[$i]=$number;
$i++;
echo $rw['total'];
$at[] = $rw['total'];
}
// the result of this query is like:
Mobile numbers bills
03455919448 34
03215350700 56
03474738923 678
03573987932 344
03187438979 1324
// now want to insert it in database
$d= 'november';
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at','$d','$num')";
mysql_error();
$result = mysql_query($sql);
}
// the insertion query at end is not working and gives me error:
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0004 sec )
I think you need to replace num with num1 like
$sql = "INSERT INTO `billing details`(bill,`month/year`,c_number) VALES ('$at','$d','$num1')";
And dont use mysql_* functions due to they are depricated,instead you use mysqli_* functions or PDO statements
AND put your table name in '`' it seems like two different names and for the column name month/year also
i dont know what exactly want to insert $num or $num1 ? and check your table name ,column names
$d= 'november';
int i=0; // you are saying that $at has all bills
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at[i]','$d','$num1[mobile_number]')";
$result = mysql_query($sql);
if (mysql_error()) die('Error, insert query failed');
i++;
}
I need to run a database query multiple times depending in the User ID. Heres my query:
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234')";
I have an array of user ID's from a seperate query shown here:
while($rows=mysql_fetch_array($allresult)){
$birthdays_today[] = $rows['user_id'];
}
echo $birthdays_today[0];
I want the query to run, but there the "userid" = XXXXX in the query, I want that to be populated with a user ID from the array. This means the query must be ran multiple times and each time, the next ID is entered into the query..
Does this make sense?
Thanks :)
MySQL has a bulk insert feature.
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234'), ('XXX2', '23234'), ('XXXX3', '3434545')"
<?php
$query = "INSERT INTO wp_scloyalty (userid, value) VALUES ";
$usersToInsert = array();
foreach($birthdays_today as $user_id){
$usersToInsert[] = "($user_id, '01234')";
}
$query .= implode(',', $usersToInsert);
?>
Use a for loop and change out the query with sprintf() and string formatting.
<?php
foreach($birthdays_today as $uid){
mysql_query(); // ...
}
?>
but
<?php
while($rows=mysql_fetch_array($allresult)){
mysql_query(); // use $rows['user_id'] here
}
?>
I will only display the script after your $birthdays_today[] has been populated.
foreach( $birthdays_today as $thisID )
{
mysql_query( "INSERT INTO wp_scloyalty (userid, value) VALUES ('{$thisID}', '01234');" );
}