Currently I had a table called crm_leads for my Leads page where I already have many records. Now for the same page I have created few new fields which is now going to be stored in another table called crm_leads_details. Now I'm storing all my POST values in an array format like so:
$main=array(
'priority'=>$this->input->post('priority'),
'lead_status'=>$this->input->post('lead_status'),
'comment'=>$this->input->post('comment'),
'sub_status'=>$this->input->post('sub_status'),
'lead_agent'=>$this->input->post('lead_agent'),
'emailopt'=>$this->input->post('emailopt')=='Y' ?'Y':'N',
// 'kitchen'=>$this->input->post('kitchen')
);
$loginid=$this->leads_model->update_lead($main,$id);
Now in my model I'm trying to use this statement to update both my tables but it does not work:
function update_lead($maindata,$id,$w=false)
{
if($w==true){
$cond=$id;
}
else{$cond['id']=$id;}
$sql = "UPDATE `crm_leads` LEFT JOIN `crm_leads_details` ON `crm_leads`.`id`=`crm_leads_details`.`leads_id`
SET ".$maindata." WHERE ".$cond;
$query = $this->db->query($sql);
print_r($this->db->last_query()); die();
return $query;
}
This gives the following output UPDATE crm_leads LEFT JOIN crm_leads_details ON crm_leads.id=crm_leads_details.leads_id SET Array WHERE Array
Additionally, since crm_leads_details is a new table there are currently no records in it so not sure if LEFT JOIN crm_leads_details ON crm_leads.id=crm_leads_details.leads_id will work here
Write the query like this
$sql = "UPDATE `crm_leads` LEFT JOIN `crm_leads_details` ON `crm_leads`.`id`=`crm_leads_details`.`leads_id`
SET ";
$i = 0;
foreach($maindata as $key=>$value) {
$i++;
$sql .= $key." = ".$value;
$sql .= ($i == count($maindata)) ? "" : " , " ;
}
$sql .= " WHERE ".$cond;
Related
// MySQL Query gets the distinct Schools in database
// The distinct schools are then stored in an array called $allSchools
$sllSchoolsQuery = "SELECT DISTINCT stud_school AS schools FROM students";
$schoolNames = mysqli_query($conn, $sllSchoolsQuery);
while ($row = mysqli_fetch_assoc($schoolNames)) {
$arraySkl[] = $row['schools'];
}
var_dump($arraySkl);
echo "<br>";
// This will loop through the associative array called $arraySkl
foreach($arraySkl as $allSchools) {
}
The code above shows a query which gets distinct values from the column stud_school (This contains school names) in a table called students. The results of the query (distinct school names) are then stored in an array called $arraySkl. I then use a foreach loop to loop through the array ($arraySkl).
I also have a function:
// FUNCTION which calculates the sum of the boys and girls for each school
function bgTotSkl($bgTotSkl_SchoolName, $conn) {
// This if statement prevents SQL injection
if(isset($bgTotSkl_SchoolName)){
$bgTotSkl_SchoolName = mysqli_real_escape_string($conn,$bgTotSkl_SchoolName);
}
// Query called $bgTotSkl_Query, uses php variable called $bgTotSkl_SchoolName inorder
// to provide an input to specify a specific school
$bgTotSkl_Query = "SELECT SUM(result_studpoints) AS totalbg, stud_gender
FROM result
JOIN students ON result.stud_id WHERE result.stud_id = students.stud_id
AND stud_school = '$bgTotSkl_SchoolName'
GROUP BY stud_gender";
$mainQuery = mysqli_query($conn, $bgTotSkl_Query);
// Above $mainQuery executes query and stores the results as a table called $mainQuery
// $data stores the results of the query for each line within while loop
while ($data = mysqli_fetch_assoc($mainQuery)) {
echo "Total $bgTotSkl_SchoolName " . $data['stud_gender'] . ": " . $data['totalbg'] . "<br>";
}
}
The function above contains another mysql query which work perfectly fine.
The problem I have is that I want to execute the results of the foreach loop which contains school names into the parameters of the function, this would then get rid of individually entering a every school name as the parameters and use the school names in the array instead:
// Executing function
bgTotSkl($allSchools, $conn);
But the problem is I do not get any output from this command.
try
function bgTotSkl($bgTotSkl_Mixed, $conn) {
!is_array($bgTotSkl_Mixed) AND $bgTotSkl_Mixed=array($bgTotSkl_Mixed);
foreach($bgTotSkl_Mixed as $bgTotSkl_SchoolName){
if(isset($bgTotSkl_SchoolName)){
$bgTotSkl_SchoolName = mysqli_real_escape_string($conn,$bgTotSkl_SchoolName);
}
$bgTotSkl_Query = "SELECT SUM(result_studpoints) AS totalbg, stud_gender
FROM result
JOIN students ON result.stud_id WHERE result.stud_id = students.stud_id
AND stud_school = '$bgTotSkl_SchoolName'
GROUP BY stud_gender";
$mainQuery = mysqli_query($conn, $bgTotSkl_Query);
while ($data = mysqli_fetch_assoc($mainQuery)) {
echo "Total $bgTotSkl_SchoolName " . $data['stud_gender']
. ": " . $data['totalbg'] . "<br>";
}
}
}
After hours of trying I need your advice.
I want to combine rows from 2 tables.
After I created a new row in table1 I want to find a row in table2 and combine some of the fields.
If I put the nested SELECT in the SET function
(SET postcode=(SELECT etc)
is works, but if I put it in the FROM function is gives an Error that the syntax is wrong
my code:
$sql = "INSERT INTO instanties(institution, category, postcode)
VALUES('$emapData[0]', '$emapData[1]', '$emapData[2]')";
if ($conn->query($sql) === TRUE) {
//get last added id
$last = $conn->insert_id;
//define WHERE function
$where="postcode_id=$postcode_id AND (minnumber <= $number AND maxnumber >= $number)";
//UPDATE last added row in table with info from other table
$sql2 = "UPDATE instanties
SET postcode_id=pc.postcode_id
FROM
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
) pc
WHERE id=$last";
$result = $conn->query($sql2);
if ($result) {
echo 'update is done<br/><br/>';
}
}
else {
echo "Error: " . $sql2 . "<br>" . $conn->error.'<br/><br/>';
}
}
else {
echo "Error: " . $sql . "<br>" . $conn->error.'<br/><br/>';
}
That's not a valid MySQL syntax. You cannot add a "FROM" clause to an UPDATE statement.
http://dev.mysql.com/doc/refman/5.0/en/update.html
However, what you want to accomplish is still possible this way:
$sql2 = "UPDATE instanties
SET postcode_id=
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
)
WHERE id=$last";
As long as there is only 1 result from the nested SELECT (and your LIMIT 1 kinda does that).
EDIT:
If you need many fields from the postcode table, you can join on it:
$sql2 = "UPDATE instanties as i
JOIN (
SELECT *
FROM postcode
WHERE $where LIMIT 1
) as pc
SET i.postcode_id=pc.postcode_id
WHERE i.id=$last";
We would usually use an "ON" clause with the join, but since you're only updating 1 row and your nested SELECT will also only return 1 row, it's not necessary.
try this:
$sql2 = "UPDATE instanties
SET postcode_id=(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1)
WHERE id=$last";
$sql = "SELECT * FROM
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
This is my query it works fine and gives the desired output,But since i am showing data in table i also want to get columns name only for this query to show them as table header .
I tried Something like this , but result is null.
$sql = "SHOW COLUMNS
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
Can anyone help ? I am not so good with mysql ; (
You need to retrieve column information after query is executed. This can be done by using mysqli_fetch_field()
You code should look like following
$result = mysqli_query($sql);
while($field = mysqli_fetch_field($result)) {
print $field->name . "\t";
}
while ($row = mysqli_fetch_row($result) {
print_r($row);
}
I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)