how to insert table count value into db using codeigniter - php

I use this following code to print the count value from the db table now i need to insert this count value into the table please help me.
$this->db->like($data);
$this->db->from('student_table');
$result= $this->db->count_all_results();
echo "count:".$result;
This only display the count value
need to insert the count value to the db table

its very simple, insert count value in database, as u have not mentioned that table name and attributes/fields in which you want to insert the count, i am putting up a general answer!
using Insert query
$this->db->like($data);
$this->db->from('student_table');
$result= $this->db->count_all_results();
$this->db->query("INSERT INTO tbl_name VALUES('$result')");
or if you want to count all rows in a table,
$result = $this->db->count_all('table_name');
Using update query
$this->db->where('id', $id); // if particular value to update
$this->db->update('tblName', $result);

Related

INSERT MULTIPLE ROWS in Gerund Table using Insert Into Select

I used INSERT INTO SELECT to copy values (multiple rows) from one table to another. Now, my problem is how do I insert rows with its corresponding IDs from different tables (since it's normalized) into a gerund table because it only outputs one row in my gerund table. What should I do to insert multiple rows and their corresponding IDs in the gerund table.
My code for the gerund table goes like this.
$insert = "INSERT INTO table1 SELECT * FROM sourcetable"; // where id1 is pk of table1.
$result =mysqli_query($conn,$insert)
$id1=mysqli_insert_id($conn);
Now table 1 has inserted multiple rows same as the other 2 tables.
Assuming id.. are the foreign keys
INSERT INTO gerundtable (pk, id1,id2,id3) VALUES ($id1,$id2,$id3);
My problem is it doesn't yield multiple rows.
According to MySql documentation:
For a multiple-row insert, LAST_INSERT_ID() and mysql_insert_id() actually return the AUTO_INCREMENT key from the first of the inserted rows. This enables multiple-row inserts to be reproduced correctly on other servers in a replication setup.
So, grab the number of records being copied, and the LAST_INSERT_ID() and you should be able to map exact IDs with each copied row.
In the lines of:
$mysqli->query("Insert Into dest_table Select * from source_table");
$n = $mysqli->affected_rows; // number of copied rows
$id1 = $mysqli->insert_id; // new ID of the first copied row
$id2 = $mysqli->insert_id + 1; // new ID of the second copied row
$id3 = $mysqli->insert_id + 2; // new ID of the third copied row
...
$mysqli->query("INSERT INTO gerundtable (pk, id1,id2,id3) VALUES ($id1,$id2,$id3)");
Thank you for trying to understand and also answering my question. I resolved my own code. I used while loop to get the ids of every row and didn't use INSERT INTO SELECT.
Here is the run down. SInce I'm just using my phone bare with my way posting.
$sqlselect = SELECT * FROM table1;
While($row=mysqli_fetch_array(table1){
$insertquery...
$id1=mysqli_insert_id($conn)
$insertgerundtable = INSERT INTO gerundtable VALUES ( $id1, $id2);
}

How to add a variable value with auto increment value in an insert query

I have a localhost and I want to do something I hope I can explain it.
I have a table named 'students' in a database named 'theway', there is a column named 's_class_id' its kind is auto increment , and in php I insert some values in this table. But I want to insert a variable+the auto increment in the column named 's_class_id'.
For example : The variable's value is 'a', and the auto increment value is '5'. I want the value which be inserted in the 's_class_id' like this 'a5'.
Any help?
If it is auto-increment, the field should be an integer. Do not think that it is possible to change it to eg: 'a5'. You could run an update query searching for the s_class_id and update another string field to set it to be 'a5'.
You can do that task by folowing method,
First you need to insert record into theway table. After record insertion mysqli_insert_id($con) will return last inserted id. Then you need to update that row by using last inserted id.
// Insert Record
mysqli_query($con,"INSERT INTO theway (s_class_id) VALUES ('a')");
// Getting last inserted id
$lastInsertID = mysqli_insert_id($con);
$updatedValue = 'a'.$lastInsertID;
// Update same row with last inserted ida
$SameRowUpdate = "UPDATE theway SET s_class_id='".$updatedValue."' WHERE id=".$lastInsertID;
if (mysqli_query($conn, $SameRowUpdate )) {
echo "Record addedd successfully";
}

php insert mysql with while loop

i want to get datas from a mySQL table and want to insert every row (that my query get) into another table.
With following code i get my Datas:
$cart = new Dbconn();
$query = new Dbconn();
if ($cart->pdo()) {
$cart->stmt("SELECT id, product FROM cart WHERE uid =:uid");
$cart->bindParam(':uid', Session::get('uid'));
$cart->exe();
}
After i get the data i want to insert it, with a while loop
while ($rowPay = $cart->fetch()) {
if ($query->pdo()) {
$query->stmt('INSERT INTO orders (products_id, order_id) VALUES(:uid, :products)');
$query->bindParam(':user_id', Session::get('uid'));
$query->bindParam(':products', $rowPay['product']);
$query->exe();
}
}
He get all Datas but insert only the first entry. Where is my mistake?
Greetings
If it insert only the first entry, then there is a problem with the parameters you try to insert.
You probably try to insert several rows with the same primary key.
I need to know where is the primary key in each table in order to help you more.
$payCart->fetch() fetches single row and $payCart->fetchAll() fetches all rows.
Try as this
while ($rowPay = $payCart->fetchAll(PDO::FETCH_ASSOC)) {
if ($query->pdo()) {
$query->stmt('INSERT INTO orders'
.'(products_id, order_id)'
.'VALUES(:uid, :products)');
$query->bindParam(':user_id', Session::get('uid'));
$query->bindParam(':products', $rowPay['product']);
$query->exe();}}

Inserting data into multiple tables not functioning correctly

I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement

How do you add the id of one record into a column on another record?

If I have two different MySQL insert functions in a document going to two different tables, how can I get the id of one record and place it in the other table?
After the first insert you can pickup the id via mysql_insert_id
tru something like this
function insert1()
{
mysql_query("INSERT .....");
return myqsl_insert_id();
}
function insert2()
{
$id1 = insert1(); // the id you want
mysql_query("INSERT ..... $id1 ");
}
you can get the last insert id by mysql_insert_id() function and then use it.
For example your first Insert query is
$insertqry1 = mysql_query("insert into tbl_name values(..,...,..)");
$lastinsertid = myqsl_insert_id();
Your second Query will be
$insertqry2 = mysql_query("insert into tbl_name(id) values('$lastinsertid')");

Categories