copy values to another mysql database - php

I have a table that displays fields sent from a form. There are buttons that can edit or delete selected row by selecting id. I want to add a button that would insert selected row to another table. I cannot get it to work.
Here's the code for the table:
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('config2.php');
// get results from database
$result = mysql_query("SELECT * FROM articles")
or die(mysql_error());
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Author</th> <th>Email</th> <th>Title</th> <th>Poem</th> <th>id</th>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['Name'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td>' . $row['title'] . '</td>';
echo '<td>' . $row['content'] . '</td>';
echo '<td>' . $row['id'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo '<td>Publish</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
Here's the code for delete function:
// connect to the database
include('config2.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];
// delete the entry
$result = mysql_query("DELETE FROM stories WHERE id=$id")
or die(mysql_error());
// redirect back to the view page
header("Location: secret.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: secret.php");
}
And here's how I think the function to insert the row to other table should look like but its not working
// connect to the database
include('config2.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id values
$id = $_GET['id'];
$name = $_GET['name'];
$email = $_GET['email'];
$title = $_GET['title'];
$content = $_GET['content'];
//upload
$result = mysql_query("INSERT into publish (name, email, title, content)
VALUES WHERE name=$name, email=$email, title=$title, content=$content")
or die(mysql_error());
// redirect back to the view page
header("Location: secret.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: secret.php");
}
I'm new at this so not sure what the correct syntax would look like in this case

Using select query
$id = $_GET['id'];
$result = mysql_query("select *stories WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$query= mysql_query("INSERT INTO publish (name, email, title, content)
VALUES ('$row['Name']','$row['Email']',$row['title'],$row['content'])");

I am not sure about any PHP related stiff but have you looked at your INSERT statement. It's completely wrong. You can't use a WHERE condition in INSERT statement as shown below
INSERT into publish (name, email, title, content)
VALUES WHERE name=$name, ....
^------ Here
Did you rather meant to use INSERT INTO .. SELECT FROM construct like
INSERT into publish (name, email, title, content)
SELECT name, email, title, content
FROM Article
WHERE name=$name, email=$email, title=$title, content=$content"
(OR) just an INSERT statement
INSERT into publish (name, email, title, content)
VALUES($name, $email, $title, $content)

Use sub select if u want but i dont know about performance in large table
Insert into tablea (name,xx,xxx) value ('select name from table b where id=x' ,'select xx from table b where id=x ', 'select xxx from table b where id=x') not tested but it shoild work

Related

Trying to connect two tables together by using id value from one table on the other

So i'm pretty new to sql and i'm trying to figure out how to connect two tables together.
I have a table named customers and a table named pets and i want to assign the pets to specific customers.
I am able to assign them a customer value but only as the id, i can't figure out how to take that id and change it to say, a customer name when i reference it back in a table that displays my data.
so for example in my customer table the
customer id = 10; customerName = "John Smith";
then i have the pets table
petId = 16; petName = Alfredo; customerId = 10;
Is there a way to reference that customerID = 10 back to the customer table from the pets table so I can pull the name of the customer instead of the id?
this is my code to display the table that list the pets query, where $row['customer'] I want to show the customer name, not the id.
Thanks
<?php
$sql = "SELECT * from pets ORDER BY petName ASC";
echo "<table class='tableInfo' cellpadding='8'>";
echo "<tr><th>Pet Name</th><th>Owner</th><th colspan='2'>Action</th></tr>";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo '<td>' . $row['petName'] .'</td>';
echo '<td>' . $row['customerId'] .'</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
Yes hi there, you can definitely do that with an inner join:
select * from pets
join customers on pets.customerId = customers.customerId
order by petName
It sounds the query may be returning an error. Perhaps print the error with:
$res = mysqli_query($con, $sql) or die ('Query failed: ' . mysqli_error($con));
while ($row = mysqli_fetch_assoc($res)) {
// Do something with row
}

Return value from SQL as button name, display text after clicking the button

I am doing a project that uses php and MySQL. I am really new to php and I have searched a lot but still haven't found a clean solution.
The problem is, firstly user inputs key words and it returns searched values(table names) to variables.
echo '<h2> Search Result: </h2>';
$searchSQL = "select distinct table_name from information_schema.columns where lower(column_name) like lower('%$search%') and table_schema='university'";
$result = $conn->query($searchSQL);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$table_name = $row['table_name'];
echo "<input type='submit' name=$table_name value=$table_name>"."<br />";
}
Now the buttons are created. If user clicks on any button,it should go further and return the column names of each table. I don't know how to do with non-static buttons.
First, don't forget to setup the actual <form>. Wrap them all up.
Second, I'd suggest, just use the same name attribute in your submit buttons:
name="table_name"
So it should look like this now:
echo '<h2> Search Result: </h2>';
$searchSQL = "
SELECT DISTINCT table_name FROM information_schema.columns
WHERE LOWER(column_name) LIKE LOWER('%$search%') AND table_schema = 'university'
";
$result = $conn->query($searchSQL);
echo '<form method="POST" action="show_colums.php">'; // opening form tag
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$table_name = $row['table_name'];
echo "<input type='submit' name='table_name' value='$table_name' /> <br/>";
// ^ don use the $table_name in the name attribute
}
echo '</form>'; // closing form tag
Don't forget to also add the action="" attribute in the form tag. Just point it to whichever PHP script that will do the form processing. For this example, just use show_columns.php
Now, just apply the DESCRIBE in that PHP file that will process the selected button:
Inside show_columns.php:
if(!empty($_POST['table_name'])) {
$table_name = $_POST['table_name']; // get input
$sql = "DESCRIBE {$table_name}"; // use DESCRIBE
$query = $conn->query($sql); // execute query
while($row = $query->fetch_assoc()) { // fetch rows
// do whatver you need to do, table or whatever you like
echo $row['Field']; // field name
}
}
Edit: Or you can be a lot safer using prepared statements on the first form:
echo '<h2> Search Result: </h2>';
$searchSQL = "
SELECT DISTINCT table_name FROM information_schema.columns
WHERE LOWER(column_name) LIKE LOWER(?) AND table_schema = 'university'
";
$stmt = $conn->prepare($searchSQL);
$search = '%' . $search . '%';
$stmt->bind_param('s', $search);
$stmt->execute();
$stmt->bind_result($table_name);
echo '<form method="POST" action="show_columns.php">';
while($stmt->fetch()) {
echo "<input type='submit' name='table_name' value='$table_name' /><br/>";
}
echo '</form>';
Instead of creating submit button create button type='button' Either using javascript/jquery or using html properties call a page which will return the table details:
echo "<input type='button' name='" . $table_name . "' value='" . $table_name .
"' onclick=\"location.href='http://yourwebsite.com?tbl=" . $table_name."'\"><br />";
You can do the same calling some js function also.

How to show 1 users mySQL information

So I have two pages. One shows all of the users who have filled out the form. On this page the ID is hyperlinked to the users individual page. On the individual page it should only show their individual information. When I do it, it still shows everyones information and I can't figure out how to change it.
This is my table for all the users.
<?php
//Establish the connection to the database server
$conn = mysql_connect("localhost","root", "MIS42520!$") or die (mysql_error());
//Tell the connection which database to user_error
mysql_select_db("assignment_3", $conn);
//Tell the database what you want, with an SQL statement
$sql = "select id, firstname, lastname, emailaddress from usertable";
//Run the sql statement against the connection
$result = mysql_query($sql, $conn) or die (mysql_error());
//Process the result set $result
print "<center><table id='adminTable' border=1>";
print "<tr><th>ID</th><th>First Name</th><th>Last Name</th> <th> Email Address</th> </tr>";
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['emailaddress'] . "</td></tr>";
}
echo "</table></center>"; //Close the table
?>
My table for the single user is essentially exactly the same but I added the following on top
$id= $_GET['id'];
Change your $sql variable to this:
$sql = "select id, firstname, lastname, emailaddress from usertable where id='".htmlentities($_GET['id'])."'";
Well.. you need to change the statement for the page of the only one user i think
Try this
$sql = "select id, firstname, lastname, emailaddress from usertable where id =".$id;
And as #jay-blanchard say in the comment, try not to use deprecated methods/clases, use prepared statements here's the link to themysqli class

PHP ID not going through url

i cannot get a row to delete as the id is not going through the url. its a simple error somewhere and i cannot find the solution after having a look around for an hour.
this page contains the information on a table:
<?php
$result = mysql_query("SELECT review, ratings, date, user FROM reviews")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Reviews Yet';
} else {
echo "<table border='0'><table width=100% border='6'><tr><th>Comments/Thoughts</th><th>Ratings</th><th>Date</th><th>User</th><th>Delete</th></tr>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['review']. "</td>";
echo "<td>" . $info['ratings']. " Stars</td>";
echo "<td>" . $info['date']. "</td>";
echo "<td>" . $info['user']. "</td>";
echo "<td>" . " <a href='deletereview.php?review_id=" . $info['review_id'] . "'>Delete</a> </td>";
echo "</tr>";
}
}
echo "</table>";
?>
it goes to deletereview.php which carries out the delete function:
<?php
session_start();
require_once '../includes/db.php';
$id = $_GET['review_id'];
$info = "DELETE FROM reviews WHERE review_id = '$id'";
mysql_query($info) or die ("Error: ".mysql_error());
echo "<h2>Review Deleted</h2>";
?>
any ideas guys?
You're not selecting the review_id in the query, so $info["review_id"] is always null.
Aside from the other answers, I'll say this:
Your database will get jacked if you do not sanitize your variables.
For instance, what happens if I pass review_id=' OR '1'='1?
DELETE FROM reviews WHERE review_id = '' OR '1'='1'
This query will delete everything in reviews.
mysql_real_escape_string() your $_GET and $_POST variables before using them in your MySQL.
You forgot to select the review_id.
$result = mysql_query("SELECT review_id, review, ratings, date, user FROM reviews")
You're not selecting review_id from the database but you use $info['review_id'] to set the ID on the URL. Just change your first line to:
$result = mysql_query("SELECT review_id, review, ratings, date, user FROM reviews")
Also you must escape the input with mysql_real_escape_string:
$id = mysql_real_escape_string($_GET['review_id']);
You have to select the review_id in the query. But also you have to check for some SQL injection, because with the GET request it's easy to delete all the table records.

Not able to delete the database(mySQL) record in PHP, where did i go wrong?

I am trying to delete the records from the users table in mysql,
the code goes like this.
if(isset($_GET['id'])) {
//create query to delete the record
$query = "DELETE FROM users WHERE id =" . int($_GET['id']) or die(mysql_error());
//execute query
if($mysqli->query($query)) {
//print number of affected rows
echo $mysqli->affected_rows. " row(s) affected";
}
else {
//print error message
echo "Error in query : $query " . $mysqli->error;
}
}
else {
echo "Could not Execute the Delete query";
}
at the same time i am iterating the records from the users table in the database and it goes like this.
//query to get records
$query = "SELECT * FROM users";
//execute query
if($result = $mysqli->query($query)) {
// see if any rows were returned
if($result->num_rows > 0) {
// if yes then print one after another
echo "<table cellpadding=10 border=1>";
while($row = $result->fetch_array()) {
echo "<tr>";
echo "<td>" .$row[0] . "</td>";
echo "<td>" .$row[1] . "</td>";
echo "<td>" .$row[2] . "</td>";
echo "<td>Delete</td>";
echo "</tr>";
}
echo "</table>";
}
$result->close();
}
the problem is, i am able to get the records from the database and display it in the browser but when i try to delete the record the first condition does not pass i.e if(isset($_GET['id'])) instead it goes to else condition and print the message "Could not Execute the Delete query " , i guess it is not able to fetch the $_GET['id'] so only it refuses to enter the if condition,
P.S :i would appreciate if someone explains me in simple words, i am a newbie to programming, thanks..
You are missing an =:
echo "<td>Delete</td>";
HERE -------------------^
"DELETE FROM users WHERE id =" . int($_GET['id']) or die(mysql_error());
Shouldn't it be intval instead? There's no function int in PHP. There's also (less preferably) the cast to int, like this: (int) $_GET['id']).

Categories