Insert random id into database - php

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);
}

Related

How to create auto increment series number using mysql query?

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

How can I echo out all values associated with the email in my table

I have a table with several columns. A user logs in with a unique email and imputs values which are in turn stored in the mysql table. How can I echo out all these values associated with the user's email? I have tried a for loop, using the table ID values, which works when you increment through consercutive values, which isn't the case with the table.
//Here's my code so far:
$rownum = "SELECT * FROM tablename";
$rowrun = mysql_query($rownum, $connect); // simply querying here
//$connect is the link to server nd database.
$rowcount=mysql_num_rows($rowrun);//getting. number of table rows, to be used in forloop
for($c=1; $c<=$rowcount; $c++){
//$c will be the stand-in for ID values from the table. which I'm using to loop.
$query = "SELECT * FROM tablename WHERE. emai='$email'; //all users will be identified by email
$row = mysql_fetch_array($rowrun); //getting array. of associated column values
$grades = $row['grades'];
$classroom = $row['classroom'];
$ID= $row['ID'];
if(!empty($grades)&&!empty($classroom)){
echo "learner from class".$classroom."has. gotten".$grade."%"
//here I want all display grades and classsroom. number obtained from the mysql table associated with user's email
}
}
?>
Here's the problem: the loop works when I have an initial value for $c and the values are consercutive. But the values on the table won't be arranged consercutively and hence the loop won't increment desirably ( $c++). Whats more, the initial ID (primary auto incrementing column) value will keep changing depending on the user.
What are my options here? Foreach loop? While loop? Select by group?
To print or echo out all values associated with the user's login email
Can't you just run one query:
$sql = "SELECT * FROM table_name WHERE email = '$email'"
This will return all matches, and then you can run this query and loop through the returned data (if any)
$resultset = $conn->query($sql);
if ($resultset->num_rows > 0) {
// echo data
} else {
// no data returned
}

PHP MySQLi query not returning value

I've tried to get this to work in several ways, but I can't get this query to return the Cost value from the database to the $cost variable:
$query2 = "SELECT Cost FROM 'item' WHERE Item = '$item'";
$cost= $db->query($query2);
It seems to be empty when I try to echo it.
(The $item variable is selected from a dropdown list generated from the item-table in the mySQL-db. This works fine and if I echo the value from $item, it returns the name of the item as expected.)
Anybody sees what I'm doing wrong?
I could post my complete code if necessary, but I believe this explanation may be sufficient.
You have to declared 'fetch_array' and Make reference this URL : http://php.net/manual/en/mysqli-result.fetch-array.php
For Example:-
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_NUM);
Change $query2 = "SELECT Cost FROM 'item' WHERE Item = '$item'"; to
$query2 = "SELECT Cost FROM item WHERE item = '".$item."'";
Assuming Cost is your column name, the first item is your table name, the second item is another column name (Please change your naming convention and not use the same name for table and column). To make your question clearer, please provide us with your table name, your column names so that we can give you a more accurate answer.
Also you will need to escape your $item variable by using '".$item."' so that you can query from your database proper using that variable.
You will then need to fetch the results from querying the database.
$results = $db->fetch_all($cost);
To test that the data were successfully fetched, you can test it by printing it using print_r($results); This should return you an array of the results.
This might help you.
$input = "100";
$query = "select sal from sal where sal='$input'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
//This will print sal
echo $row['sal'];
Please let me know if you've any questions.
$query=mysql_query("SELECT Cost FROM item WHERE Item = '$item'");
while($x=mysql_fetch_array($query))
{
$cost=$x['Cost'];
echo $cost; //here we can return the result
}

echo updated values instead of old values

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'].",,";
}

How to generate next auto increment number in mysql using php?

I was trying to fetch next auto increment number in mysql using php. I tried this way:
<?
$q=mysql_query("SELECT * FROM `users`");
$next_auto_inc=mysql_num_rows($q)+1;
?>
But, this when any row is deleted don't work. I hope you got what I mean. How can I do this using php?
You can't do that fetching the table data. You have to fetch the table status to get the auto increment number using php. And that, you can do something like this:
$q = mysql_query("SHOW TABLE STATUS LIKE 'test'");
$row = mysql_fetch_assoc($q);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
Hope this helps :)
[Source]
Assuming that you have user_id column as primary key you can also try this:
$q = mysql_query('SELECT MAX(user_id) as user_id from `users`');
$row = mysql_fetch_assoc($q);
$next_auto_inc = $row['user_id'] + 1;

Categories