I have a table populated by a MySQL table, and I am trying to insert the selected rows from the table into another table.
The table look like below:
.
There are first three fields in the table are coming from two other tables depending on the Field values.
And the drop down selections are provided by user using:
$sql = "SELECT project_proposals.id, project_proposals.title, project_proposals.description, project_proposals.academicname, flux_student_records.studentname, flux_student_records.id, flux_student_records.programme, flux_student_records.academicdiscipline FROM project_proposals JOIN flux_student_records ON project_proposals.academicdiscipline = flux_student_records.academicdiscipline
WHERE project_proposals.academicdiscipline = '$academicdiscipline' AND flux_student_records.studentname = '$studentname'";
$retval = mysql_query($sql) or die(mysql_error());
What will be the best way to insert these multiple selected rows into another table please? Thanks.
"select into" is the way to go.
SELECT into YourNewTable select project_proposals.id, project_proposals.title, project_proposals.description, project_proposals.academicname, flux_student_records.studentname, flux_student_records.id, flux_student_records.programme, flux_student_records.academicdiscipline FROM project_proposals JOIN flux_student_records ON project_proposals.academicdiscipline = flux_student_records.academicdiscipline
WHERE project_proposals.academicdiscipline = '$academicdiscipline' AND flux_student_records.studentname = '$studentname'";
Hope you find this usefull.
You can loop trough an post and then do some thing with that information.
So for example:
<?php
function readDataForwards($dbh) {
$sql = 'SELECT * FROM yourdb';
try {
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
#insert the data into another database
#you can also filter some duplicated items that you already
#have in the database
}
$stmt = null;
}
catch (PDOException $e) {
print $e->getMessage();
}
}
?>
this would output: the rows in the database
but it could also insert the rows into your database.
Related
Hello I have one MySql database with 4000 tables. All the tables have same data structure. I want to retrieve data from one column "name" which is inside all the tables. I want to list all that data.
I had searched through google, stack overflow and many more resources. But I don't find any specific answer to do this without join or union. As I don't want to write that 4000 names in query. Is there any general query to do it fast. I think that might be possible to get data using information schema table but I don't know how.
As I know how to select tables:
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('Product')
AND TABLE_SCHEMA='YourDatabase';
But I don't know query to get data out of them.
Thank You.
You have php tag. So I think you can easily get your data in php.
try {
$dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'password');
//Get all table name
$sth = $dbh->query("SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('name') AND TABLE_SCHEMA='ai'");
// build your query string
$query = ' ';
foreach ($sth->fetchAll() as $table) {
$query .= "SELECT DISTINCT name from $table[0] UNION ";
}
$queryWithoutLastWord = preg_replace('/\W\w+\s*(\W*)$/', '$1', $query);
// execute your final query
$sth1 = $dbh->query($queryWithoutLastWord);
// Now build your expected array
$names = [];
foreach ($sth1->fetchAll() as $name) {
$names[] = $name['name'];
}
print_r($names);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
I'm a Mysql/php novice and I'm trying to get several results of one query.
I have a db named "my_db", who has a table named "my_table". This table has only one column named "fruits". I inserted some elements in items like banana, pineapple, coconuts and apple.
I would like to display all this items so I tried this code:
$sql = 'SELECT items FROM my_table';
$req = mysql_query($sql) or die('Erreur SQL !<br />'.$sql.'<br />'.mysql_error());
$data = mysql_fetch_array($req);
mysql_free_result ($req);
echo $data['items'];
But this only show me the first element of the column "items" (here, banana).
How can I show a list of all the elements ?
Thanks in advance !
If you use mysql, then you need to create cycle, for excample "while cycle":
$sql = mysql_query("SELECT * FROM lietotajs");
while($row = mysql_fetch_array($sql ))
{
echo $row['ID'];
}
You have to run while loop after running the query, other wise it will restrict to single.
Try to do this, not tested. Hopes it will help
$sql = 'SELECT items FROM my_table';
$req = mysql_query($sql) or die('Erreur SQL !<br />'.$sql.'<br/>'.mysql_error());
while($data = mysql_fetch_array($req)){
echo $data['items'];
}
I am looking for how to insert multiple records from a SQL table into a session variable, or into multiple unique session variables.
$userID = $_SESSION['user']['id'];
$coursequery = "
SELECT
coursename,
location,
description
FROM courses
WHERE
teacherID = '$userID'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
$_SESSION['courseinfo'] = $row;
The table "courses" has a few records inside, all with the teacherID being that of the current userID, defined at the start. When I print_r($_SESSION['courseinfo']); it only displays one of the records in the table.
I'm trying to create a loop that displays all the information grabbed, for each record, since you won't know for sure how many records you'll grab at any given time. Any answers are greatly appreciated!
$userID = $_SESSION['user']['id'];
$coursequery = "
SELECT
coursename,
location,
description
FROM courses
WHERE
teacherID = '$userID'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
while ($row = $stmt->fetch()):
$row['YourColumn'];
endwhile;
Use while() loop to fetch all record as per your query
You can fetch all your records with changing the fetch -> fetchAll() doc
$rows = $stmt->fetchAll();
Sessions can also store arrays and objects (they get serialized automatically). So you can just store the whole results set there.
$_SESSION['courseinfo'] = $rows;
Side note: Consider using another storage place for all of the returned data, if its a lot, and in the session store only Ids.
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.
I'm using a multiple select option form to get a table of venues. Each venue has an ID and this is what I used:
<?php
require("db_access.php");
if(isset($_POST['select3']))
{
$aVenues = $_POST['select3'];
if(!isset($aVenues))
{
echo("<p>You didn't select any venues!</p>\n");
}
else
{
$nVenues = count($aVenues);
echo("<p>You selected $nVenues venues: ");
for($i=0; $i < $nVenues; $i++)
{
echo($aVenues[$i] . " ");
}
echo("</p>");
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $aVenues);
echo $comma_separated;
}
}
?>
It results in this:
However I thought that the code would use those two numbers below and draw out a table with those id's I used :/ ? Am I missing something?
$array is used in implode(",", $array); but is not defined anywhere else that we can see. It is perhaps intended to be:
implode(",", $aVenues);
UPDATE
Per comments, it does not draw a table because you never actually query your database.
You build your SQL statement, but you need to execute it and fetch the result set.
// Make sure you actually have a database connection
$conn = mysql_connect('localhost', $username, $password);
mysql_select_db($database);
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $array);
echo $comma_separated;
// Execute query and fetch result rowset
$result = mysql_query($sql);
if ($result) {
$rowset = array();
while ($row = mysql_fetch_array($result)) {
$rowset[] = $row;
}
var_dump($rowset);
}
else echo mysql_error();