I do have an array something like this:
[cuisines] => Array
(
[0] => 17
[1] => 20
[2] => 23
[3] => 26
)
Now I need to update mysql table with these values. All values belong to one user.
So I tried it like this:
if (isset($_POST['cuisines'])) {
$cuisines = $_POST['cuisines'];
} else {
$error_alert[] = "Please select at least one cuisine";
}
if (empty($error_alert)) { // If everything's OK...
// Make the update query:
$sql = 'UPDATE restaurant_cuisines
SET restaurant_id = ?
, cuisine_id = ?
WHERE restaurant_id = ?';
$stmt = $mysqli->prepare($sql);
// Bind the variables:
$stmt->bind_param('iii', $restaurant_id, $cuisine_id, $restaurant_id);
foreach ($cuisines as $value) {
$cuisine_id = $value;
// Execute the query:
$stmt->execute();
}
// Print a message based upon the result:
if ($stmt->affected_rows >= 1) {
echo 'updated';
}
// Close the statement:
$stmt->close();
unset($stmt);
}
But this query not updating mysql correctly. This is what I get running this script.
mysql> select * from restaurant_cuisines where restaurant_id = 4;
+---------------+------------+
| restaurant_id | cuisine_id |
+---------------+------------+
| 4 | 26 |
| 4 | 26 |
| 4 | 26 |
+---------------+------------+
3 rows in set (0.00 sec)
What would be the problem of this script?
Hope somebody may help me out.
Thank you.
You need to bind your parameters in the loop:
// Delete old entries:
$sqlDelete = 'DELETE FROM restaurant_cuisines WHERE restaurant_id = ?';
$stmtDelete = $mysqli->prepare($sqlDelete);
$stmtDelete->bind_param($restaurant_id);
$stmtDelete->execute();
$stmtDelete->close();
unset($stmtDelete);
// now prepare to insert new values
$sqlInsert = 'INSERT INTO restaurant_cuisines (restaurant_id,cuisine_id)
VALUES (?,?)';
$stmtInsert = $mysqli->prepare($sqlInsert);
foreach ($cuisines as $value) {
// Bind the variables:
$stmtInsert->bind_param($restaurant_id, $value);
// Execute the query:
$stmtInsert->execute();
// Print a message based upon the result:
if ($stmtInsert->affected_rows >= 1) {
echo 'updated';
}
}
// Close the statement:
$stmtInsert->close();
unset($stmtInsert);
Related
I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}
I am trying to update multiple rows in a database. I have the total number of rows in my table counted and bound to a variable:
$result = '32'
I then attempt to query each row:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'];
$substrate_desc = $_POST['substrate_desc'];
$substrate_base = $_POST['substrate_base'];
$substrate_tax = $_POST['substrate_tax'];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
My problem is when I run this script, each row in the table is filled with the last row edited. For example:
AAA | Aaaaa | 1.00 | 6.35
BBB | Bbbbb | 2.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
Becomes:
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
How can I fix this script so it will update each row individually?
Try this:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'][$x];
$substrate_desc = $_POST['substrate_desc'][$x];
$substrate_base = $_POST['substrate_base'][$x];
$substrate_tax = $_POST['substrate_tax'][$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
I changed the "name" fields in my form to include the substrate's ID:
<input name="substrate_name_'.$substrate_id.'" />
Then did the same for the update query (where the id is defined by the loop, $x):
$substrate_name = $_POST['substrate_name_'.$x];
$substrate_desc = $_POST['substrate_desc_'.$x];
$substrate_base = $_POST['substrate_base_'.$x];
$substrate_tax = $_POST['substrate_tax_'.$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
And this gave me the desired result. Thanks to Rimon Khan for the idea and to everyone who commented.
I have four Array consisting of some values. I want to insert Array with same index in same row.
Eg:
$product = [Facebook, Twitter];
$sub_product = [Likes, Boost];
$plan = [10k, 20k];
$months = [3,6];
I want table to be some thing like this
+----+----------+-------------+------+--------+
| id | product | sub_product | plan | months |
+----+----------+-------------+------+--------+
| 1 | Facebook | Likes | 10k | 3 |
+----+----------+-------------+------+--------+
| 2 | Twitter | Boost | 20k | 6 |
+----+----------+-------------+------+--------+
What will be the best way to achieve this such that Index of each array falls in same row? I want to insert in HTML table
If you want to execute mysql_query in single shot then
$product = [Facebook, Twitter];
$sub_product = [Likes, Boost];
$plan = [10k, 20k];
$months = [3,6];
$query = 'insert into TABLE (product,sub_product,plan,months) values';
foreach( $product as $index => $col ){
$query .= "( '".$product[$index]."', '".$sub_product[$index]."', '".$plan[$index]."', ".$months[$index]." ),";
}
$query = rtrim( $query, ',');
mysqli_query(mysql_query);
This will be faster than executing multiple mysql_query function in a loop.
Try This Code,
foreach($product as $key=>$p){
$data = array(
'product'=>$p,
'sub_product'=>$sub_product[$key],
'plan'=>$plan[$key],
'months'=>$months[$key]
);
//Code to insert this array to Database
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO `table`('product','sub_product',...) VALUES ($data['product'],$data['sub_product'],...)";
mysqli_close($conn);
//OR If you are using Codeigniter,
$this->db->insert('table',$data);
}
this code should work,
$product = array("Facebook", "Twitter");
$sub_product = array("Likes", "Boost");
$plan = array("10k", "20k");
$months = array(3,6);
for($i=0;$i<count($product);$i++){
$product_name=$product[$i];
$sub_product_name=$sub_product[$i];
$plan_name=$plan[$i];
$month_no=$months[$i];
echo "insert into table_name (product_name, sub_product_name, plan_name, month_no) values ('$product_name', '$sub_product_name', '$plan_name', '$month_no')";
echo "<br>";
}
Thanks
Amit
Assuming all arrays have the same length and $mysqli is a connection to your database,
for ($i=0; $i < count($product); $i++) {
$query = "INSERT INTO your_table (id, product, sub_product, plan, months)";
$query .= " VALUES ('$i', '{$product[$i]}', '{$sub_product[$i]}', '{$plan[$i]}', '{$months[$i]}')";
$mysqli->query($query);
}
Assuming that the size of all the above arrays are same at a given point of time and their indexing is consistent you can use the following code:
<?php
$product = array('Facebook', 'Twitter');
$sub_product = array('Likes', 'Boost');
$plan = array('10k', '20k');
$months = array(3,6);
/* Connected to a mysql Database */
$i = 0; //initialize a counter
while($i < sizeof($product)) //Run the loop (Twice in this case)
{
//Store the current iteration value in variables
$current_product = $product[$i];
$current_sub_product = $sub_product[$i];
$current_plan = $plan[$i];
$current_months = $months[$i];
//Prepare the SQL statement
$sql = <<<EOD
INSERT INTO table_product(product,subproduct,plan,months)
VALUES ('$current_product','$current_sub_product','$current_plan',$current_months)
EOD;
$i++;
echo $sql . "<br />";
}
?>
Do on this way simple:
$count = count($product);
$index=0;
while($index<$count){
//do your stuff here i.e. insert query
$sql = "INSERT INTO your_table SET product='".$product[$index]."', sub_product='".$sub_product[$index]."', plan='".$plan[$index]."', months='".$months[$index]."' ";
mysql_query($sql);
$index++;
}
I'm trying to fetch the result of a query to my database. I have no problems doing so when the resultset is just 1 row, but when it's multiple rows I only get the first one.
Here is my db:
-----keys-------------------
| id | key_nbr | date |
----------------------------
| 42 | abc123 | xxxx |
| 49 | 789xyz | wxyz |
----------------------------
My function:
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
$row = $stmt->fetch_array(MYSQLI_ASSOC);
return $row;
}
}
return null;
}
Output when doing print_r($row); is only the first row:
Array ( [id] => 42 [key_nbr] => abc123 [date] => xxxx) How to make it print all rows?
You have to check for total number of rows before fetching the data, if it's not zero then execute the loop and fetch all records.
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
if($stmt->num_rows != 0) {
$row = array();
while($r = $stmt->fetch_array(MYSQLI_ASSOC)) {
$row[] = $r;
}
return $row;
}
}
}
return null;
}
I'm starting to work with big data.
My input is a daily csv files with many columns and I've to import these three columns:
user_id
parent_id
grandparent_id
.....
what is my goals?
I have to count all the unique user_id values belonging to two grandparent_id (12345 and 67890) and group them by parent_ids
I have to count all the no exclusive unique user_id values belonging to two grandparent_id (12345 and 67890) and group them by parent_ids
I've designed this data model with three tables (thank to Rock that suggested me to use counter in my previous post)
CREATE TABLE container_u_id (
parent_id int,
user_id text,
grandparent_a boolean,
grandparent_b boolean,
PRIMARY KEY (parent_id, user_id)
)
CREATE TABLE unique_u_id (
parent_id int,
counter_uu counter,
PRIMARY KEY (parent_id)
)
CREATE TABLE no_exclusive_unique_u_id (
parent_id int,
counter_uu counter,
PRIMARY KEY (parent_id)
)
For importing the data I'm using php and the pdo driver for Cassandra.
Here my script
$relpath = realpath(dirname(__FILE__)) . '/';
include_once($relpath."config/init.php");
$dsn = "cassandra:host=127.0.0.1;port=9160";
$db = new PDO($dsn);
$db->exec("USE phpcassa");
$array_grandparent_id = array(12345, 67890);
$file_csv = new CSVFile("file.csv");
foreach ($file_csv as $row) {
$user_id = $row['USER_ID'];
$parent_id = $row['PARENT_ID'];
if(in_array($row['GRANDPARENT_ID'], $array_grandparent_id)){
$is_grandparent_a = ($row['GRANDPARENT_ID']==12345) ? 'TRUE' : 'FALSE';
$is_grandparent_b = ($row['GRANDPARENT_ID']==67890) ? 'TRUE' : 'FALSE';
$query= "INSERT INTO container_u_id (user_id, parent_id, grandparent_a, grandparent_b) VALUES('".$user_id."', ".$parent_id.", ".$is_grandparent_a.", ".$is_grandparent_b." ) IF NOT EXISTS;";
$stmt = $db->prepare($query);
$status_exec = $stmt->execute();
$result_insert = $stmt->fetchAll();
$is_uu = ($result_insert[0]['[applied]']) ? True : False;
if($is_uu===False){
$status_grandparent_a = $result_insert[0]['grandparent_a'];
$status_grandparent_b = $result_insert[0]['grandparent_b'];
//if user belong to both grandparents then it is already present onto both counter tables
if($status_grandparent_a===False || $status_grandparent_b===False){
if($status_grandparent_a===False && $is_grandparent_a=='TRUE'){
$query = "UPDATE container_u_id SET grandparent_a = true WHERE user_id='".$user_id."' AND parent_id = ".$parent_id.";";
$stmt = $db->prepare($query);
$status_exec = $stmt->execute();
$query= "UPDATE no_exclusive_so SET counter_uu = counter_uu + 1 WHERE parent_id = ".$parent_id.";";
$stmt = $db->prepare($query);
$status_exec = $stmt->execute();
}elseif($status_grandparent_b===False && $is_grandparent_b=='TRUE'){
$query = "UPDATE container_u_id SET grandparent_b = true WHERE user_id='".$user_id."' AND parent_id = ".$parent_id.";";
$stmt = $db->prepare($query);
$status_exec = $stmt->execute();
$query= "UPDATE no_exclusive_so SET counter_uu = counter_uu + 1 WHERE parent_id = ".$parent_id.";";
$stmt = $db->prepare($query);
$status_exec = $stmt->execute();
}
}
}
if($is_uu){
$query= "UPDATE unique_u_id SET counter_uu = counter_uu + 1 WHERE parent_id = ".$parent_id.";";
$stmt = $db->prepare($query);
$status_exec = $stmt->execute();
}
}
}
Then starting from this csv sample
Yzc4Jknl0-3c, 34, 12345
Yzc4Jknl0-3c, 34, 67890
Yzc4Jknl0-3c, 34, 12345
01w44Xz0w3c1, 13, 12345
01w44Xz0w3c1, 21, 12345
01w44Xz0w3c1, 21, 12345
qFxg0023Exy4, 21, 67890
At the end of the code the table are showing these results
SELECT * FROM container_u_id;
parent_id | user_id | grandparent_a | grandparent_b
-----------+--------------+---------------+--------------
34 | Yzc4Jknl0-3c | True | True
13 | 01w44Xz0w3c1 | True | False
21 | 01w44Xz0w3c1 | True | False
21 | qFxg0023Exy4 | False | True
SELECT * FROM unique_u_id;
parent_id | counter_uu
-----------+------------
34 | 1
13 | 1
21 | 2
SELECT * FROM no_exclusive_unique_u_id;
parent_id | counter_uu
-----------+------------
34 | 1
Now, let's start to talk my doubts.
The script works but it's very slow. For fetching 50 million rows the script spends between 8 and 10 hours.
The dev environment is:
ubuntu 12.04 64 bit
cqlsh 4.1.1
Cassandra 2.0.6
CQL spec 3.1.1
Thrift protocol 19.39.0
cpu: i3 M 370
storage: rotating disk 5400rpm
Ring: cluster with single node
Thus I'd like to improve the performance...my question is:
is there anything wrong on my data modeling?
Do I need to add more nodes and change the hardware(aws ec2)?