I have a conversation table and conversation reply table:
conversation table:
+-------+-------+--------+
| cid | u_1 | uid_2 |
+-------+-------+--------+
| 1 | 8 | 3 |
| 2 | 8 | 5 |
| 3 | 8 | 2 |
+-------+-------+--------+
conversation_reply table:
+-------+-------+--------+--------+
| cr_id | reply | uid_fk | cid_fk |
+-------+-------+--------+--------+
| 1 | | 8 | 1 |
| 2 | | 8 | 11 |
| 3 | | 8 | 11 |
+-------+-------+--------+--------+
I need to be able to update the conversation table with a new record if one doesn't exist when a new reply is created, however I get the following error:
Cannot add or update a child row: a foreign key constraint fails
(`_db`.`conversation_reply`, CONSTRAINT `conversation_reply_ibfk_2`
FOREIGN KEY (`cid_fk`) REFERENCES `conversation` (`cid`))
Any help much appreciated!!!!
EDIT
I have put the convo reply query into the create new convo query, it will create a new convo but still doesn't insert the reply:
if (!empty($_GET['conv_id'])) {
$cid = mysql_real_escape_string($_GET['conv_id']);
echo $cid;
}
if($user_one!=$user_two){
// Check convo doesn't already exist.
$q_exist= mysql_query("SELECT c_id FROM mc_conversation WHERE (user_one='$user_one' and user_two='$user_two') or (user_one='$user_two' and user_two='$user_one') ") or die(mysql_error());
if(mysql_num_rows($q_exist)==0) {
$query = mysql_query("INSERT INTO mc_conversation (user_one,user_two,ip,time) VALUES ('$user_one','$user_two','$ip','$time')") or die(mysql_error());
$q=mysql_query("SELECT c_id FROM mc_conversation WHERE user_one='$user_one' ORDER BY c_id DESC limit 1");
$v=mysql_fetch_array($q);
return $v['c_id'];
$v_cid = $v['c_id'];
// Insert reply.
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$v_cid')") or die(mysql_error());
// Convo already exists.
} else {
$v=mysql_fetch_array($q_exist);
return $v['c_id'];
// Insert reply
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$cid')") or die(mysql_error());
echo $cid;
}
}
You have called "return" in your else loop, which will end execution of the function, or if called from the global scope, execute the current script.
http://php.net/manual/en/function.return.php
Try this:
// Insert reply
$v=mysql_fetch_array($q_exist);
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$cid')") or die(mysql_error());
echo $cid;
From the code that you have posted I think the problem is with the return statement.
The reply is not getting inserted because you have
return $v['c_id'];
before the INSERT query code. And if this code is inside a function, it will just return the value and not execute any further line.
You should have the return statement at the very end of the function / after doing all required operations. If it is for debugging purpose, you can use echo statement.
Related
I'd like to fetch data from my 2 sql database and do some math and post the result in database
let's say my table1 is like this
+---+---+----------------------------+
| A | B | C |
+---+---+----------------------------+
| 2 | 9 | result from A*B*D*E in php |
| 1 | 8 | result from A*B*D*E in php |
| 4 | 7 | result from A*B*D*E in php |
| 3 | 6 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 6 | 5 | result from A*B*D*E in php |
| 5 | 4 | result from A*B*D*E in php |
+---+---+----------------------------+
and my table2 is like this
+---+----+
| D | E |
+---+----+
| 1 | 9 |
| 2 | 7 |
| 3 | 8 |
| 4 | 6 |
| 5 | 5 |
| 6 | 3 |
| 7 | 2 |
+---+----+
so far what i've done
// database connection
include_once("config.php");
// Query
$query = mysqli_query($conn, "SELECT * FROM table1");
$query2 = mysqli_query($conn, "SELECT * FROM table2");
//Source1
while($user_data1 = mysqli_fetch_array($query))
{
$A[] = $user_data1['A'];
$B[] = $user_data1['B'];
}
//Source2
while($user_data2 = mysqli_fetch_array($query2))
{
$D[] = $user_data2['D'];
$E[] = $user_data2['E'];
}
foreach (array_combine($A, $B) as $ValueA=> $ValueB)
{
foreach (array_combine($D, $E) as $ValueD=> $ValueE)
{
$result1 = $ValueA*$ValueB*ValueD*ValueE;
$val = 0.123;
$result2[] = $result1*$val;
}
$final result = min($result2);
echo round($final result, 2);
unset($result2);
}
I haven't inserted the database yet
still echoing for debug if the math is correct
somehow this code found some bug
for example using my database the final result only echo/showing 6 math result
because in table1 row 5 and 6 has same data
btw of course in my table1 and 2 has primary key
To change C in this case, you don't even need PHP. To UPDATE a value in MySQL with multiple tables just add them with a , when selecting the tables, like this:
UPDATE table1,table2 SET C = table1.A * table1.B * table2.D * table2.E WHERE C IS NULL;
Executing this code once will update all rows so that C = A*B*D*E as wanted where C is not yet set or NULL. If you want to update all rows you can just remove the WHERE condition
Note: Sometimes (at least for me) SQL will give a warning when having no WHERE condition in the SQL query. To bypass this just add WHERE 1=1 at the end.
Just for my understanding: you want to calculate a value for your calculation you need some data from table 1 that is clear, but also from table2 But which one? I guess you want to use the data from the same row ( so row 1 from table1 and row 1 from table2, row 2 from table 1 and row 2 from table2 ) right? Now you have an problem because when you make a select * from table You do not know in which order they give back from your database. Most time it may be the same order as you have input them, but there is no garantie. You have sayed you have an primary key on each table, how have you defined them? I guess you may have a id column, so you can join your table on that id?
-----------------------------------------------------
| id | posts_id | users_id | ratings |
-----------------------------------------------------
| 1 | 7 | 20 | 5 |
| 2 | 8 | 20 | 3 |
| 3 | 7 | 21 | 4 |
-----------------------------------------------------
Table name: mytable
\I want to make sure that ratings between posts_id and users_id are matched on the same column.
$query = $conn->query("SELECT ratings FROM mytable WHERE posts_id=7 and users_id=20");
$row = $query->fetch_array();
echo $row['ratings'];
This query does not work. I know there must be something wrong.
I want to get results: 5
What is the best query to show ratings?
----------------UPDATE-----------------------------
Sorry, my first problem lies with the connection, and now it is resolved.
But now there is a new problem.
I want to display the total sum of the rating results.
My new code
$Rate = $conn->query("SELECT * FROM mytable WHERE posts_id=7");
while ($Rated = $Rate->fetch_array()) {
echo $Rated['ratings'] + $Rated['ratings'];
}
For example on posts_id=7
Here I expect 5 + 4 = 9
But my code results exactly 54 + 54
How to fix this code?
For the updated question, this code should be work. We can use sum() function. Check here sum() function
$Rate = $conn->query("SELECT sum(ratings) as ratings FROM mytable WHERE posts_id=7");
while ($Rated = $Rate->fetch_array()) {
echo $Rated['ratings'];
}
I have a table student, table structure is follow
student_id | name | class|
-------------------------
2-12-2013 | test | 3 |
-------------------------
2-13-2013 |test2 | 5 |
-------------------------
in this table i want add new record, its student_id become 2-14-2013. For that i want to get the last inserted student_id. how can i get it by MySQL query. Am alredy use mysql_insert_id() But its not working, How to solve this issue?
Define Your student table like below:-
student_id | add_date | name | class|
--------------------------------------
1 | 2013-12-2 | test | 3 |
--------------------------------------
2 | 2013-13-2 |test2 | 5 |
--------------------------------------
student_id would be int auto increamented primary key
then execute Query like below to get last inserted id:-
select student_id from student order by student_id desc limit 1;
Hi You has to set primary key to your table as integer auto-increment then you can use this last inserted id
$con = mysql_connect("localhost", "root", "", "chirag2");
$sql = "INSERT INTO test_student ( student_id,name,class)values('3-12-2013','test1','3' )";
$res = mysql_query($con, $sql);
echo mysql_insert_id($con);
die;
Note: you need to truncate table before alter it and set new primary key to it so take backup before this
I need to fetch data from table whose mem_count is equal to 2 and then insert that data to another table after last unique_id.
Here is my code :
$mem_count2=mysql_query("SELECT mem_count,mem_id FROM member_status WHERE mem_count = 2 order by mem_id ASC");
if(mysql_num_rows($mem_count2 )==0){
die(mysql_error());
}
else{
$start_value=00;
// $start_value dynamically comes from other table which i am not mentioning here
// $start_value can starts from any number For Eg. 2, 5.
while ($row=mysql_fetch_array($mem_count2)) {
$uniq_code="PHR-" . str_pad((int) $start_value, 2, "0", STR_PAD_LEFT);
//if mem_id already inserted then use IGNORE in INSERT i.e INSERT IGNORE
$cql = "INSERT IGNORE INTO member_code (mem_id, temp_code,unique_code) values ('".$row['mem_id']."','".$row['mem_count']."','".$uniq_code."')";
mysql_query($cql) or exit(mysql_error());
$start_value++;
}
}
It runs smoothly but sometimes i am getting this output:
+------------+-------------+
| mem_id | unique_code |
+------------+-------------+
| 1 | PHR-01 |
+------------+-------------+
| 5 | PHR-02 |
+------------+-------------+
| 3 | PHR-04 |
+------------+-------------+
Some problem is surely in the INSERT IGNORE query!I have made mem_id as UNIQUE. Please rectify this as i am completely stuck over it !
Member_code structure
+------------+-------------+-----+
| mem_id | unique_code | Id |
+------------+-------------+-----+
| 1 | PHR-01 | 1 |
+------------+-------------+-----+
| 5 | PHR-02 | 5 |
+------------+-------------+-----+
| 3 | PHR-04 | 3 |
+------------+-------------+-----+
It is probably because you are getting an error at some point at this line
mysql_query($cql) or exit(mysql_error());
and then your increment variable will be incremented for the next insert. You should test the insert and if doesn't get error you do the increment.
You are using a variable called $mem_count2 throughout your code, when the results are stored in $mem_count.
I have a deals table with the following data:
dealID | date | followUP | user
1 |2012-10-15 | Yes |
2 |2012-12-24 | Yes |
3 |2013-01-05 | |
4 |2013-02-02 | Yes |
5 |2013-02-02 | Yes |
And a users table with my users list
userID | name
1 | john
2 | eric
3 | anne
What I would like to do is to query the first table that has followUP set as 'YES' then from the result assign a user to them in sequence from the users table so my final deals table will look like this
dealID | date | followUP | userID
1 |2012-10-15 | Yes | 1
2 |2012-12-24 | Yes | 2
3 |2013-01-05 | |
4 |2013-02-02 | Yes | 3
5 |2013-02-02 | Yes | 1
I know its a loop but for some reason i cant figure out how to setup the second loop to assign the value of the users. Any help would be appreciated.
First get your user IDs into an array so it looks:
$uids = array(1, 2, 3);
Then, when reading the records from deals table compose update queries like so:
$follow_up_user_idx = 0;
$update_queries = array();
while($row=mysqli_fetch_assoc($result)) {
// ... do whatever you need to
if($row['followUP'] != 'Yes') continue;
$update_queries[] = "UPDATE `deals` SET `user` = '" . $uids[$follow_up_user_idx] . "'
WHERE `dealID` = '" . $row['dealID'] . "' LIMIT 1";
$follow_up_user_idx++;
if($follow_up_user_idx > count($uids) - 1) $follow_up_user_idx = 0;
}
Now you have all update queries. Just execute them:
foreach($update_queries as $uq) {
mysqli_query($link, $uq);
}
You will have to follow a series of steps to achieve what you have mentioned.
1) Fetch all the records from database where followUP is 'Yes'.
Lets say that first table is deals. So, fetch all records where followUP is 'Yes'.
Lets say, you have result in $deals_details.
2) Fetch all the users(name) from database.
Lets say that second table is users. So, fetch all users.
Lets say, you have all users' names in $users_details array.
Get a count of total users in system in seperate variable say $users_count.
3) Loop through $deals_details and assign each user one-by-one sequentially from $users_details.
$i = 0;
foreach($deals_details as $keyDD => $valueDD){
$user = $users_details[$i];
$i++;
if($i == $users_count)
$i = 0;
$query = "update `deals` set user = '".$user."' where dealID = '".$valueDD['dealID']."'";
//fire query
//$link is connection variable.
mysqli_query($link, $query);
}
Table user
+---------------+---------------+------------+
| user_id | username | user_level |
+---------------+---------------+------------+
| 1 | superadmin | admin |
| 2 | subadmin | admin |
| 3 | team1 | team |
| 4 | team2 | team |
| 5 | team3 | team |
| 6 | customer1 | customer |
| 7 | customer2 | customer |
| 8 | customer3 | customer |
| 9 | customer4 | customer |
+---------------+---------------+------------+
Table complaint:
+---------------+---------------+------------+
| complaint_id | complaint | user_id |
+---------------+---------------+------------+
| 1 | os issue | 7 |
| 2 | USB issue | 8 |
| 3 | OS currepted | 7 |
| 4 | HD issue | 9 |
| 5 | DVD issue | 6 |
| 6 | SW problem | 9 |
| 7 | Network issue| 9 |
| 8 | system issue | 6 |
+---------------+---------------+------------+
Table assign_work
+---------------+------------+
| complaint_id | user_id |
+---------------+------------+
| 1 | 3 |
| 2 | 4 |
| 3 | 5 |
| 4 | 3 |
| 5 | 4 |
| 6 | 5 |
| 7 | 3 |
| 8 | 4 |
+---------------+------------+
When customer raise the complaint data should save in complaint table also that last
complaint_id should save in assign_work table at the same time
user_id also save sequencially, fetch from user table who are the team that person id only.
I m new in ph please any one help me.
This may be a poor design decision. Without knowing more about your application, I'd be tempted to wait for a user to become available/request a deal, then assign to them (from a queue) the next deal requiring follow-up. Even if you have good reasons to assign users before they are "available", you might consider doing so upon deal creation/modification based on some appropriate business logic (e.g. maintaining a queue of users to be assigned to the next deal).
Indeed, there's no particularly nice way of performing this operation with a simple UPDATE statement. One way to accomplish it purely within the database would be to use a stored procedure (it's not especially concurrency-safe though, as changes to the Users table between closing and reopening the _curUser cursor may cause undesirable effects; one might instead copy the Users to a temporary table for the purposes of this procedure, depending on your desired logic):
DELIMITER //
CREATE PROCEDURE assignDeals() BEGIN
DECLARE _userID, _dealID BIGINT UNSIGNED;
DECLARE _done BOOLEAN DEFAULT FALSE;
DECLARE _curUser CURSOR FOR
SELECT userID
FROM users
ORDER BY userID;
DECLARE _curDeal CURSOR FOR
SELECT dealID
FROM deals
WHERE followUP = 'Yes'
ORDER BY dealID
FOR UPDATE;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET _done := TRUE;
PREPARE stmt FROM 'UPDATE deals SET userID = ? WHERE dealID = ?';
OPEN _curUser;
OPEN _curDeal;
readDeal: LOOP
FETCH _curDeal INTO _dealID;
IF _done THEN
LEAVE readDeal;
END IF;
FETCH _curUser INTO _userID;
IF _done THEN
SET _done := FALSE;
CLOSE _curUser;
OPEN _curUser;
FETCH _curUser INTO _userID;
IF _done THEN
SIGNAL SQLSTATE VALUE '45000' SET
MESSAGE_TEXT = 'No users';
LEAVE readDeal;
END IF;
END IF;
SET #userID := _userID, #dealID := _dealID;
EXECUTE stmt USING #userID, #dealID;
END LOOP readDeal;
CLOSE _curUser;
CLOSE _curDeal;
DEALLOCATE PREPARE stmt;
END//
DELIMITER ;
See it on sqlfiddle.