MySQL insert row from HTML table into db table - php

I am using a for loop to construct a HTML table from the contents of a MySQL table select query. I have a link on the end of each row to copy that row into another table.
I'm unsure how to get the data from the table row for the MySQL insert query - I have marked the place where I'm struggling with XXX.
<?php
mysql_select_db("cardatabase");
$link = mysql_connect("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query($query);
if($_GET['rent']) {
$rent = "INSERT INTO rentedcars VALUES('XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr><td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td></tr>";
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_object($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
edit (updated code):
<?php
mysql_select_db ("cardatabase");
$link = mysql_connect ("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query ($query);
if($_GET['rent']) {
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']);
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt);
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr>";
echo "<td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td>";
echo "</tr>";
while ($row = mysql_fetch_object($result)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";

mysql_* is deprecated as of PHP 5.5.0, you should use something like PDO.
try {
$DBH = new PDO('mysql:dbname=cardatabase;host=localhost', 'root', 'password');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$STH = $DBH->query("SELECT * FROM cars")->execute();
while ($row = $STH->fetch(PDO::FETCH_OBJ)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=".$row->ID."'>Rent</a></td>
</tr>";
}
Edit: Just like #Skatox said!

I would do it like this:
<?php
$link = mysql_connect ("localhost", "root", "password");
mysql_select_db ("cardatabase");
$query = "SELECT * from cars";
$result = mysql_query ($query);
Get car information and store it
if($_GET['rent'])
{
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']); //Avoids sql injection
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt)
Here you need to validate if there's no car
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
Change it to while like #Vinoth Babu said:
while ($row = mysql_fetch_object ($result))
{
$row = mysql_fetch_object ($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
print "</table>";
?>
I would recommend you to switch to MySQL PDO, it's safer and you'll get a better and secure code.

you are missing the column names in your insert query
$rent = "INSERT INTO rentedcars (id ,carmake, carmodel,fueltype,transmission, enginesize,doors,amount ,available, dateadded)
VALUES('xxx','xxx','".$carmodel."','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
^^^^^-------------i showed u exempel under
those XXX are values you get the from the inputs values
exemple
<input name= "car_model" id= "car_model" value="mercedes" >
then you get this value
if (isset($_POST['car_model'])){ $carmodel = $_POST['car_model']}
and then use this value $carmodel in your sql

Related

How to get variable from header in multi query?

i already had forms where I got the variable from the header but the forms have always been pdo and always one single query. This form is connected via mysqli and I just can't figure out how to get a variable.
<?php
$mysqli = new mysqli("localhost:3307", "root", "root", "test");
if($mysqli->connect_errno)
die ("Connection failed".$mysqli->connect_error);
$query = "SELECT * FROM contacts WHERE id = ?;";
$query .= "SELECT * FROM companies WHERE id = ?;";
if($mysqli->multi_query($query)) {
do{
$result = $mysqli->store_result();
$finfo = $result->fetch_fields();
echo"<table border ='1'>";
echo "<tr>";
foreach($finfo as $f) {
echo "<th>".$f->name."</th>";
}
echo "<br>";
echo "<br>";
echo "</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
foreach($row as $v) {
echo "<td>".$v."</td>";
}
echo "</tr>";
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
?>
So the column "id" in both tables is the PK/FK and I want to retrieve information where id = ?.
How do I get the ? variable from the header and pass it on?
I feel like in my past tries I got the variable successfully with this code
$id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');
[...]
$statement = $mysqli->prepare($query);
$statement->bindParam(1, $id);
$statement->execute();
but didn't echo it correctly.
Thank you in advance!

Cannot get URL from Database to link

I am doing a project and would be eternally grateful for help in getting my URl's to link. I have tried looking around to no avail. I have a database (4columns). The last one (link1) should link to videos with the specified URL.When the table comes up the URL's are not clickable (is there a way to simplify this say "click me"?). Here is my code. I've also attached an image of the table. This is really busting my brains, thanks.
<?php
$con = mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM videos";
$result = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>
<th>topic1</th>
<th>subject1</th>
<th>link1</th>
</tr>";
while( $row = mysqli_fetch_array( $result)) {
$topic1 = $row["topic1"];
$subject1 = $row["subject1"];
$link1 = $row["link1"];
echo "<tr>
<td>$topic1</td>
<td>$subject1</td>
<td>$link1</td>
</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Table output
Try this:
<?php
$sql = "SELECT * FROM `videos`";
$result = mysqli_query($con, $sql);
?>
<table>
<?php
while($row = mysqli_fetch_assoc( $result)) {
?>
<tr>
<td><?php echo $row['topic1'];?></td>
<td><?Php echo $row['subject1'];?></td>
<td><a href="<?php echo $row['link1']; ?>" target="_blank">Click me</td>
</tr>
<?php } ?>
<table>
Or you can also use do while loop:
do{
echo '<tr>';
echo '<td>'.$row['topic1'].'</td>';
echo '<td>'.$row['subject1'].'</td>';
echo '<td><a href="'.$row['link1'].'" target="_blank">Click me</td>';
echo '</tr>';
} while($row = mysqli_fetch_assoc( $result);
I added the target attribute to open the link in a new window.
I looked at your code and i found a couple errors.
change $con = mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test"); to $con = new mysqli("localhost", "feedb933_charles", "pass100", "feedb933_test");
Then change if (mysqli_connect_errno()) to if (mysqli_connect_error()) {
Then change
$sql = "SELECT * FROM videos";
to
$sql = "SELECT topic1, subject1, link1 FROM videos";
or if you want to select one row
$differentvalue = ""; // value to run
$sql = "SELECT topic1, subject1, link1 FROM videos WHERE difvalue = ?";
difvalue is the value different frm the rest so the php code knows what to grab.
Using stmt means no sql injection
Add:
$stmt = $con->stmt_init();
if (!$stmt->prepare($sql))
{
print "Failed to prepare statement\n";
}
else
{
}
Then in side if (something) { } else { IN HERE }
(if you have WHERE diffvalue) Add:
$stmt->bind_param("s", $differentvalue); // $stmt->bind_param("s", $differentvalue); if text, $stmt->bind_param("i", $differentvalue); if integer
Then
Add:
$stmt->execute();
$list = $stmt->fetchAll();
then outside the if (something) { code } else { code }
Add:
echo "<table><tr><th>topic1</th><th>subject1</th><th>link1</th></tr><tr>";
foreach ($list as $row => $new) {
$html = '<td>' . $new['topic1'] . '</td>';
$html .= '<td>' . $new['subject1'] . '</td>';
$html .= '<td>' . $new['link1'] . '</td>';
echo $html;
}
echo "</tr></table>";
If you are still having problems goto the links listed
http://php.net/manual/en/pdostatement.fetchall.php
http://php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-result.fetch-all.php
Hope this helps
<?php
$con=mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM videos";
$result = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>
<th>topic1</th>
<th>subject1</th>
<th>link1</th>
</tr>";
while( $row = mysqli_fetch_array( $result)) {
$topic1 = $row["topic1"];
$subject1 = $row["subject1"];
$link1 = $row["link1"];
echo "<tr>
<td>$topic1</td>
<td>$subject1</td>
<td>$link1</td>
*//this href will give u the link as u asked. //be sure you store proper url. In case of exact video name saved in column thn can make the url for your web output. //ex:<a href="http://example.com/'.$link.'.extension">*
</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Update mysql function to mysqli

I would like to update this code to be mysqli, but dont know where to begin.
I know that the connection is handled like this , buts thats as far as iv got.
$connection = mysqli_connect('localhost', 'admin', 'admin', 'database_name');
Function to be updated:
$cn=mysql_connect('localhost', 'admin', 'admin') or die(mysql_error());
mysql_select_db('database_name',$cn) or die(mysql_error());
$sql = "SELECT name FROM category";
$rs = mysql_query($sql) or die(mysql_error());
echo "<select>";
while($row = mysql_fetch_array($rs)){
echo "<option value='".$row["name"]."'>".$row["name"]."</option>";
}mysql_free_result($rs);
echo "</select>";
<?php
$sql = mysqli_query($connection, 'SELECT name FROM category');
echo "<select>";
while($row = mysqli_fetch_array($sql)){
echo "<option value='".$row["name"]."'>".$row["name"]."</option>";
}mysql_free_result($sql);
echo "</select>";
?>
$cn=mysqli_connect('localhost', 'admin', 'admin','database_name') or die(mysqli_error($cn));
$sql = "SELECT name FROM category";
$rs = mysqli_query($cn,$sql) or die(mysqli_error($cn));
echo "<select>";
while($row = mysqli_fetch_array($rs)){
echo "<option value='".$row["name"]."'>".$row["name"]."</option>";
}mysqli_free_result($rs);
echo "</select>";
You can learn about mysqli on PHP's website Mysqli Book
But for security and other benefits you should now use PDO instead

Call to a member function query() on a non-object on line

I can't seem to figure out what is going on here... or why this isn't working. The code works on a different database... so I'm not sure what is going on?
<?php
//connect to the database
$con = new mysqli("localhost", "rreedy", "quixtar1");
$con->select_db("attendance");
//display success or failure
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . $con->connect_errno;
}
echo "<label for='evtCode'>Event</label><br/>";
echo "<select id='evtCode' class='form-control' name='evtCode'>";
echo "<option value=1>Text</option>";
$query = "SELECT * from tbldata";
$result = $con->query($query);
while($row = mysqli_fetch_array($result))
echo $row['courseName'];
echo "</select>";
?>
You have a typo, it should be:
$result = $con->query($query);
Your mysqli object is in $conn. You're also mixing procedural and object oriented together.
echo "<option value=1>Text</option>";
$query = "SELECT * from tbldata";
$result = $con->query($query);
while($row = $result->fetch_array(MYSQLI_ASSOC))
echo $row['courseName'];
echo "</select>";
What I changed
$con->query()
$row = $result->fetch_array(MYSQLI_ASSOC)
The docs
query
fetch_array

PHP Output of SQL Query

As of now I have no errors in my program, but I need the primary key for one of the tables for a relation for the following Query. but instead of getting a actual number the value the query is sending back is Resource id #4
Here is my Code: (The query that I'm having issues with is the $sql_branch, is there a function to change the result from "Resource id #4" to just 4?
$sql_branch = "SELECT BranchNum
FROM Branch
WHERE BranchName = '$_POST[branch]'";
$sql_result = "SELECT AuthorFirst, AuthorLast, OnHand, Title
FROM Inventory i, Wrote w, Author a, Book b
WHERE i.BookCode = b.BookCode AND i.BookCode = w.BookCode
AND a.AuthorNum = w.AuthorNum AND i.BranchNum = 1";
$connect = mysql_connect('students', 'xxxx', 'xxxx') or exit(mysql_error());
mysql_select_db('henrybooks', $connect);
if(mysql_query($sql_branch, $connect)) {
$branch = mysql_query($sql_branch, $connect);
}
else {
echo mysql_error();
}
if(mysql_query($sql_result, $connect)) {
$result = mysql_query($sql_result, $connect);
}
else {
echo mysql_error();
}
echo $branch."<br>";
echo $sql_branch."<br>";
echo "<table>
<tr>
<td>Author</td>
<td>Title</td>
<td>Number Available</td>
</tr>";
while( $row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row['AuthorFirst'].$row['AuthorLast']."</td>";
echo "<td>".$row['Title']."</td>";
echo "<td>".$row['OnHand']."</td>";
echo "</tr>";
}
echo "</table>";
?>
Thanks!
You are not pulling results from the mysql_query. Try this:
if($branch_result = mysql_query($sql_branch, $connect)) {
$branch = mysql_fetch_array($branch_result);
}

Categories