code:
<?php
$this->db->select('*');
$this->db->from('bugs');
$where = "project_name = '".$project."'";
$this->db->where($where);
$sql = $this->db->get();
$res = $sql->num_rows();
if($res === 0)
{
$i = 1;
foreach ($bug as $row)
{
echo $i;
}
}
else
{
$i = 1;
foreach ($bug as $row)
{
echo ++$i;
}
}
?>
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
In this code I have a table name bugs where I have a column i.e. bug_id. Now, I want to insert data into my table if table row having no value it insert bug_id = 1 and after that insert 2 and then 3 and so on. But now when I click on submit button it insert bug_id = 1 and then 2 but when I click on third it insert again bug_id 2 . So, How can I fix this problem?Please help me.
Thank You
MySQL has integrated AUTO_INCREMENT. Either you log into phpMyAdmin and change the properties of your bug_id field by clicking on edit, then selecting the "A_I" field.
Or you can do it with a SQL query:
ALTER TABLE YOUR_TABLE MODIFY bug_id INTEGER NOT NULL AUTO_INCREMENT;
If #Twinfriends answer doesn't fit your needs (but that should be the correct way to do that, you shouldn't reinvent the wheel) then maybe the problem is with your:
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
Since you are actually using $this->input->post('bug_id') as your new id, maybe you want to use something else?
Where does your $bug var come from? To be sure of not getting duplicated ids or wrong one you could add to your MySql query something like "ORDER BY bug_id DESC LIMIT 1" (so that you take 1 row as result with the highest bug_id) and then just use that result + 1 as the new id
Related
I have a sql query in my php:
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
Now, I have to echo back several HTML tables based on different orderIds, so basically if the orderId is changed, a new HTML table will be created and contains the info of all the things under this orderId. This is what I have done(kinda pseudocode, please ignore the syntax error. My real code is far more complicated but the idea is here: set an oldOrderId and check it with the newly fetched orderId and see if the orderId is changed):
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
for ($i = 0; $i<$count + 1; $i++ ){
if ($row = $stmt->fetch()){
$orderId = $row["orderId"];
$2ndField = $row["2ndField"];
$3rdField = $row["3rdField"];
...
// check if $oldOrderId is set
if (isset($oldOrderId)){
// and compare, if the orderId changes, end the table and create a new one
if ($oldOrderId != $orderId){
echo "</table><br>";
echo "<table><tr><th>...</th></tr>";
...
//UPDATE old orderId
$oldOrderId = $orderId;
// if orderId doesn't change, continue echo table content
} else {
echo "<table><tr><td>...</td></tr>";
}
// if the oldOrderId is not set, it means this is the first fetched row, and the very first table will be created
} else {
echo "<table><tr><th>...</th></tr>";
...
echo "<table><tr><td>...</td></tr>";
...
//SET oldOrderId
$oldOrderId = $orderId;
}
}
if ($i == $count) {
//End the last table
echo "</table><br>";
}
}
The code can run but will be buggy sometimes and I don't think this is a smart way to identify it. Is there any existed method like
$row = $stmt->fetch().prev()
to get the last row's orderId's value? Or if there's any better way to perform it?
Thanks!
The problem is your inclusion of GROUP BY orderId in your query. What this does is give you one row per each orderId in your table.
Since you are using SELECT *, then all you are getting back is one row for each orderId and one of the other values in the table for each of the other fields.
When using GROUP BY, you usually want to add a "group function" - like SUM(), COUNT(), GROUP_CONCAT(), etc. - to your query.
Your approach with the $oldOrderId is fine and could work if you change your query to something like:
SELECT * FROM orderTaken
WHERE orderStatus='10'
ORDER BY orderID DESC, orderTakenTime DESC
Currently i am doing a PHP GET and getting values after clicking the submit button.
I got the values out from the submit button but I dont know how to reference them to the values in column.
For example, after clicking the submit button, I get the value 1.
Inside my database i have 3 columns
Col 1 Col 2 Col 3
2 3 1
How do i get the COLUMN name by just having the value itself? Thank you so much!
Ugly/silly, but would do what you want:
Query:
SELECT * FROM yourtable WHERE 1 in (col1, col2, col3, ... ,colN)
and then manually pick out the value in client code:
$row = mysql_fetch_assoc($result);
$matches = array_search(1, $row);
var_dump($matches);
You can't get away from listing all of the columns in the query, because there's no WHERE x IN (*)-type construct.
I would do it like this.
Get all table columns
then loop throug results and run select for each column
$columnVsValue = array();
foreach($columns as $column) {
$q = "SELECT id FROM table where {$column} = {$value}";
if(TRUE) { // you have to check that query return value
$columnVsValue[] = $column;
}
}
I did it quick probably there is more efficient way to do it
I am using PHP and I want to make a table with the rows Orderid, ID, Employee_Name, and Employee_Salary. I want two ID columns because I am trying to allow the user to be able to move a table row up or down to change the order of the table rows. Apparently, from what I have read, the only way to do this is by having an ID column and an Order ID column in order to manipulate the order of the table rows.
Here is the code I am trying to use to move the rows up and down. For example I want the user to be able to click an up arrow button to change Row 1: Kelsey, Row 2: Max, to Row 1: Max, Row 2: Kelsey.
PHP Code:
<?php
// Variables -- Fill these out from the results of your page. (i.e. what item id to move up or down)
$id_item = 1; // ID of item you want to move up/down
$isUp = true; // Change to false if you want to move item down
// MySQL structure -- Fill these out to execute your queries without needing to update my code
$table_name = "employee"; // Name of table with your items in it
$col_position = "position"; // Name of column with position ID (Remember, this must be UNIQUE to all items)
$col_id = ""; // Name of column containing the items id (most likely the auto_incremented column)
if ($isUp)
{
$operator = "<";
$order = "DESC";
}
else
{
$operator = ">";
$order = "ASC";
}
// Get row we are moving
$request = mysql_query("
SELECT '.$col_position.', '.$col_id.' FROM '.$table_name.'
WHERE '.$col_id.' = '.$id_item.'
LIMIT 1");
// Save data for row we are moving
if(mysql_num_rows($request) > 0) {
$isPos1 = true;
while($row = mysql_fetch_assoc($request)) {
$position1 = $row[$col_position];
$id_item1 = $row[$col_id];
}
}
// Get row we want to swap with
$request2 = mysql_query("
SELECT '.$col_position.', '.$col_id.' FROM '.$table_name.'
WHERE '.$col_position.' '.$operator.' '.$position1.'
ORDER BY '.$col_position.' '.$order.' LIMIT 1");
// Save data from row we want to swap with
if(mysql_num_rows($request2) > 0) {
$isPos2 = true;
while($row = mysql_fetch_assoc($request2)) {
$position2 = $row[$col_position];
$id_item2 = $row[$col_id];
}
}
// If both rows exist (indicating not top or bottom row), continue
if ($isPos1 && $isPos2)
{
$query_update = mysql_query("
UPDATE '.$table_name.'
SET '.$col_position.' = '.$position2.'
WHERE '.$col_id.' = '.$id_item1.'");
$query_update2 = mysql_query("
UPDATE '.$table_name.'
SET '.$col_position.' = '.$position1.'
WHERE '.$col_id.' = '.$id_item2.'");
}
?>
The queries for updating the order should look something like this, just using an ID of 5 for the modified item and a new orderID of 2, for the sake of the example:
UPDATE table SET orderID=2 WHERE ID=5;
UPDATE table SET orderID=orderID+1 WHERE ID!=5 AND orderID >= 2;
Sorry I didn't have time to tailor it specifically to your table setup, but this should definitely put you on the right track.
How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}
I'm trying to insert records in my database and I am using this code:
<?php
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("my_db");
$patient_array = array();
$query = "SELECT * FROM accounts";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$patient_array[$row['account_id']] = array("lastname" => $row['lastname'],
"firstname" => $row['firstname']);
}
foreach($time_table as $tid => $t){
echo array_rand($patient_array, 1);
echo $tid."====".$t["from"]." - " . $t["to"]."<br />";
$sql = "INSERT INTO appointment (appt_id, appt_date, appt_time, appt_doctor,
patient_id, appt_time_end) VALUES ('', '".$appt_date."', '".$t["from"]."',
'".$doc."', '".$tid."', '".$t["to"]."')";
mysql_query($sql);
}
?>
This one is properly inserting but for the "patient_id" I want to store random ids. $tid gives me random output but when I check the database, it's not the same; it's showing ids in descending order. I tried using Order by Rand() but I can't figure out how to make it working. Any idea? Or am I missing something?
Thanks!
EDIT: I am getting the patient_id from another table, which is the accounts table to be passed into appointment table. I was able to select random patient ids but how can I insert it to another table, in random order also.
For getting random id why cant you use the functoin uniqid() in PHP
$randomID = uniqid()
Please refer the following link,
Random/Unique ID
you can add an extra column called 'time' where you put the UNIX time for example so that when you order by the 'time' you get the random ids in the order you wrote them in the table..
I suggest you to add the time is really useful to have it stored somewhere!
if you want them not in random order but in a precise order I don't actually understand why you wanna use the random id though!
I would make a database field called id which has the
AUTO_INCREMENT attribute
You can add the column with the following command
alter table appointment add (id INT NOT NULL AUTO_INCREMENT);
Thank you for all your responses, but I've figured out what's the answer for this. Here's my code modification:
while($row = mysql_fetch_array($result))
{
//I changed this...
//$patient_array[$row['patient_id']] = array("lastname" => $row['lastname'], "firstname" => $row['firstname']);
//to this:
$patient_array[] = $row['patient_id'];
}
foreach($time_table as $tid => $t){
/*
removed this, since it's just an output to check what's happening inside
the 'rand'
echo array_rand($patient_array, 1);
echo $tid."====".$t["from"]." - " . $t["to"]."<br />";
*/
//added these...
$rand = array_rand($patient_array); //randomize patient id
$patient_id = $patient_array[$rand];
print_r($patient_id); //displays randomized ids
//and now was able to INSERT RANDOM patient ids
$sql = "INSERT INTO appointment (appt_id, appt_date, appt_time, appt_doctor, patient_id, appt_time_end) VALUES ('', '".$appt_date."', '".$t["from"]."', '".$doc."', '".$patient_id."', '".$t["to"]."')";
mysql_query($sql);
}