MYSQL Query Mass Pump - php

$sql = "INSERT INTO `coupon` SET
`name` = 'FREECOUPON',
`coupon_code` = '" . $this->db->escape($couponCode) . "',
`discount` = '38',
`uses_total` = '22',
`status` = '1'
";
$this->db->query($sql);
$coupon_id = $this->db->getLastId();
$this->db->query("INSERT INTO coupon_cat SET coupon_id = '" . (int)$coupon_id . "', category_id = 79 ");
The query works, but I want to modify this
$this->db->query("INSERT INTO coupon_cat SET coupon_id = '" . (int)$coupon_id . "', category_id = 79 ");
I want to "mass pump" data into coupon_cat. I need to pump from category 30-180, but in different lines. Any idea how to do it ?

If I understand you clear you want to insert the same coupon_id to 150 category ids. You can insert all the rows in one query using loop to create all the values.
$coupon_id = (int)$this->db->getLastId();
$values = [];
for ($category_id = 30; $category_id <= 180; $category_id++) {
$values[] = '(' . $coupon_id . ',' . $category_id . ')';
}
$this->db->query('INSERT INTO `coupon_cat` (coupon_id, category_id) VALUES ' . implode(',', $values));

Related

Insert multiple items into a database row and return the results separated by commas

Is there a way to insert multiple items into a database row then return the results and their counter part as commas?
For instance:
POST
POSTID URL HITS
1 http://google.com,http://facebook.com 35,20
So say post 1 has the 2 urls in it, google has 35 hits, while facebook has 20. now I want to show that result using something like:
$query = $db->query_first("
SELECT * FROM ". TABLE_PREFIX ."post
WHERE url = '" . $drc_url . "'
");
But I only want to pull one URL at a time with its corresponding hits value. Is this possible? If so can someone point me in the right direction?
right now my php looks like:
$query = $db->query_first("SELECT * FROM ". TABLE_PREFIX ."post WHERE url = '" . $drc_url . "'");
if (!$query){
$db->query_write("INSERT INTO ". TABLE_PREFIX ."redirect (url, hits) VALUES ('" . $drc_url . "', 1)");
} else {
$db->query_write("UPDATE ". TABLE_PREFIX ."redirect SET hits = hits + 1 WHERE url = '" . $drc_url . "'");
}
but if theyre in the same $postid I want them to all get put in the same row
See the comments in code.
$drc_url = "http://google.com";
/* insert/update */
$query = $db->query("SELECT * FROM ". TABLE_PREFIX ."post WHERE url LIKE '%" . $drc_url . "%'");
if ( $query->num_rows > 0 ) {
// the URL can be in multiple rows - go through each row
while( $row = $query->fetch_assoc() ) {
//find the URL position/index within the list
//if it's possible that the URLs are already separated by anything else than comma (for example "comma and space", "space", etc), you need to add functionality to be able to find them correctly
$urls = explode( ',', $row[ 'url' ] );
$index = array_search( $drc_url, $urls );
//same as previous comment goes for the hits row
$hits = explode( ',', $row[ 'hits' ] );
//increment the hits number on the correct value
$hits[$index]++;
//update the hits (put them back as a string from the array with already incremented value) - use unique identificator in the WHERE clause
$db->query("UPDATE ". TABLE_PREFIX ."redirect SET hits = '" . implode( ',', $hits ) . "' WHERE postid = '" . $row[ 'postid' ] . "'");
}
} else {
// the URL was not found - insert
$db->query("INSERT INTO ". TABLE_PREFIX ."redirect (url, hits) VALUES ('" . $drc_url . "', 1)");
}
/* select */
//same functionality as above, just not updating
$query = $db->query("SELECT * FROM ". TABLE_PREFIX ."post WHERE url LIKE '%" . $drc_url . "%'");
while( $row = $query->fetch_assoc() ) {
$urls = explode( ',', $row[ 'url' ] );
$index = array_search( $drc_url, $urls );
$hits = explode( ',', $row[ 'hits' ] );
echo "URL " . $drc_url . " has " . $hits[$index] . "hits";
}
But as Mark Baker wrote in the comment, it would be much better to change the DB structure and then build on the new structure.

Stuck with INSERT INTO ON DUPLICATE KEY UPDATE

I have the following query:
INSERT INTO `impressions` (`date`, `item_id`, `platform`, `country`) VALUES ('" . $date . "', '" . $item_id . "', '" . $platform . "', '" . $country . "') ON DUPLICATE KEY UPDATE `impressions` = `impressions` + 1
And the following array:
Array
(
[0] => 5
[1] => 2
[2] => 4
[3] => 17
)
The array basically consists of item_ids, which I want to insert/update in to the database.
When the query runs, I want it to check to see if there are any rows which are from: today, match the specificed item_id, match the specified platform and match the specified country.
For example:
2015-03-05 5 mobile US (new insert)
2015-03-05 2 mobile UK (new insert)
2015-03-05 5 mobile US (this would +1 impression from first one)
2015-03-05 17 desktop US (new insert)
2015-03-06 5 mobile US (this would create a new insert because the date doesn't exist)
I also want to pass an array of item_ids, as specified above using IN, to avoid multiple looping.
Right now we are currently doing it like this:
$item_ids = array('5', '2', '4', '17');
foreach($item_ids as $id){
$q = mysql_query("SELECT `id` FROM `impressions` WHERE `date` = '" . $date . "' AND `item_id` = '" . $id . "' AND `platform` = '" . $platform . "' AND `country` = '" . $country . "'");
if (mysql_num_rows($q)){
$r = mysql_fetch_array($q);
mysql_query("UPDATE `impressions` SET `impressions` = `impressions` + '1' WHERE `id` = '" . $r['id'] . "'");
} else {
mysql_query("INSERT INTO `impressions` (`date`, `item_id`, `platform`, `country`, `impressions`) VALUES('" . $date . "', '" . $id . "', '" . $platform . "', '" . $country . "', '1') ");
}
}
We basically want to convert this huge (and badly coded) loop, into 1 mySQL INSERT/UPDATE query which gets passed an array of item_ids to be used with IN.
I am really confused how I should approach this. Any help would be greatly appreciated.
UPDATE impressions = impressions + 1
needs to be
UPDATE impressions = VALUES(impressions) + 1
INSERT INTO `impressions` (
`date`,
`item_id`,
`platform`,
`country`,
`impressions`
)
VALUES (
'{$date}',
{$id},
'{$platform}',
'{$country}', '1')
ON DUPLICATE KEY
UPDATE `impressions` = VALUES(impressions) + 1
for this to work, see to it that the table impressions has a primary key to check with.
so that the on duplicate key it will update it

insert with a select statement and php variables in 1 MySQL query

i have something like this to insert data from a form to my MySQL table. is my use of select statements in the insert valid? please enlighten me.
if(isset($_POST['date']) && isset($_POST['docName']) && isset($_POST['docSpec']) && isset($_POST['time']) && isset($_POST['symptoms']) )
{
$nameOfUser = $_COOKIE['userlogin'];
$docName = $_POST['docName'];
$date = $_POST['date'];
$symptoms = $_POST['symptoms'];
$time = date('H:i:s',strtotime($_POST['time']));
$id = mt_rand(1000,9999); //generate random appointment id
$insertQuery = "insert into appointment values
($id,(select doctorid from doctors where doctorName like '$docName' ),
$date,$symptoms,
(select patientid from patient where patientFName like '$nameOfUser'), $time)";
if(mysqli_query($conn,$insertQuery)===true)
{
echo "<script>alert('success');</script>";
}
else
{
die('Invalid query: ' . mysql_error());
$message .= 'Whole query: ' . $query;
die($message);
}
}
it says invalid query. the columns in the insert statement is already in right order. can anyone help me?
You have to specify the columns that you are inserting into -
insert into appointment (col1, col2, col3, ...) values
($id,(select doctorid from doctors where doctorName like '$docName' ), $date,$symptoms,(select patientid from patient where patientFName like '$nameOfUser'),$time)";
It looks like you have 6 columns.
EDIT: This syntax may help to clear things up -
$insertQuery = "INSERT INTO `appointment` (`col1`, `col2`, `col3`,`col4`,`col5`,`col6`) ";
$insertQuery .= "VALUES (";
$insertQuery .= "'" . $id . "'";
$insertQuery .= ", '" . "(SELECT `doctorid` FROM `doctors` WHERE `doctorName` LIKE '%" . $docName . "%')" . "'";
$insertQuery .= ", '" . $date . "'";
$insertQuery .= ", '" . $symptoms . "'";
$insertQuery .= ", '" . "(SELECT `patientid` FROM `patient` WHERE `patientName` LIKE '%" . $nameOfUser . "%')" . "'";
$insertQuery .= ", '" . $time . "'";
$insertQuery .= ")";
You're also using LIKE without giving it the chance to find other elements because you're not using wildcards.

Update field Error in MySQL statement

I am trying to update a MySQL database field (decrease the value by 1) in a specific row (ID) of the "places" column, as long as the number in the field is greater than 0.
(see the example statement below)
UPDATE table SET places = places - 1 WHERE id = $id AND places > 0
The statement below fails apart from changing the value of the field to zero.
I would be grateful if anyone can help with the syntax error.
if($id){
global $modx;
$table = "`database_name`.`table_name`";
$update_seats = "`places` - 1";
$result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );
return $result; // Returns 'true' on success, 'false' on failure.
}
You have enclosed new value of field in double quotes
$result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );
what is evaluated as string in MySQL query. Remove double quotes here
'`places` = "' . $update_seats . '"'
so that it looks like this
$result = $modx->db->update( '`places` = ' . $update_seats, $table, '`id` = "' . $id . '" AND `places` > 0' );
The query looks ok, if you need to set minimum value of 1 to places you should simply change the query accordingly:
UPDATE table SET places = places - 1 WHERE id = $id AND places > 1

Insert into mysql and php using array

I have part of the code below:
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONTPAY."VALUES ($array[\"username\"], $array[\"password\"], '0',$array[\"userid|\"], )";
$second_result = $database->query($second_query);
}
The query doesn't seem to work. Any clues? I think it's a problem with the quotes or something. How can actually pass array elements?
here is my whole code i want to move one row to another table
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO" . TBL_USERSDONTPAY . "VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] ."')";
$second_result = $database->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
You need to clean that query up and remove the final comma.
$second_query = "INSERT INTO " . TBL_USERSDONTPAY . " VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
I see several issues with your query code
escaping of the array indexes in your string:
you can either end the string and concatenate the parts together:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
or use the {$var} syntax:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
missing spaces (see example code above .. you were missing the spaces before and after the table name)
missing field names. your query may work without if you specify all fields in the right order, but will fail misteriously when you alter the table later (e.g. add a field to the table)
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" (username, password, foo, user_id)".
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
please note you should actually insert the correct field names in the second line of my example above. You can find more information on this in the MySQL docs for INSERT

Categories