How to get variable from header in multi query? - php

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!

Related

php GridView table while row as link

I've been searching about what i want and nothing..
If someone knows a tutorial or something like.
What i want is...
I've a got table made in php... and i add a "link to get the id",
echo "<td><a href='profile.php?id=" . $row['id'] . "'>Details</a></td>";
using the ID from the transaction to show a full details from that ID. in the same page.
My question is... How can i show that id details... as a new table with that details.?
You need to add condition in your file with that table (I am assuming it is the profile.php file).
If your code looks something like this:
$mysqli = new mysqli("localhost", "user", "password", "database");
$result = $mysqli->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "<table>";
echo "<tr>";
...
echo "<td><a href='profile.php?id=" . $row['id'] . "'>Details</a></td>";
...
echo "</tr>";
echo "</table>";
}
Just change it this way:
$mysqli = new mysqli("localhost", "user", "password", "database");
if (!empty($_GET['id'])) {
$id = $mysqli->real_escape_string($_GET['id']);
$result = $mysqli->query("SELECT * FROM users WHERE id=".$id);
$row = $result->fetch_assoc();
echo "User data: <br>";
echo "Name: ".$row['name']."<br>";
...
} else {
$result = $mysqli->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "<table>";
echo "<tr>";
...
echo "<td><a href='profile.php?id=" . $row['id'] . "'>Details</a></td>";
...
echo "</tr>";
echo "</table>";
}
}

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

Displaying all records in a mysql table

The code below works fine for printing one record from a database table, but what I really want to be able to do is print all the records in the mysql table in a format similar to my code.
I.E.: Field Name as heading for each column in the html table and the entry below the heading. Hope this is making sense to someone ;)
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
$num_fields = mysql_num_fields($raw);
$num_rows = mysql_num_rows($raw);
$i = 1;
print "<table border=1>\n";
while ($i < $num_fields)
{
echo "<tr>";
echo "<b><td>" . mysql_field_name($field, $i) . "</td></b>";
//echo ": ";
echo '<td><font color ="red">' . $allresults[$i] . '</font></td>';
$i++;
echo "</tr>";
//echo "<br>";
}
print "</table>";
Just as an additional piece of information you should probably be using PDO. It has more features and is helpful in learning how to prepare SQL statements. It will also serve you much better if you ever write more complicated code.
http://www.php.net/manual/en/intro.pdo.php
This example uses objects rather then arrays. Doesn't necessarily matter, but it uses less characters so I like it. Difference do present themselves when you get deeper into objects, but not in this example.
//connection information
$user = "your_mysql_user";
$pass = "your_mysql_user_pass";
$dbh = new PDO('mysql:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
//prepare statement to query table
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
//loop over all table rows and fetch them as an object
while($result = $sth->fetch(PDO::FETCH_OBJ))
{
//print out the fruits name in this case.
print $result->name;
print("\n");
print $result->colour;
print("\n");
}
You probably also want to look into prepared statements. This helps against injection. Injection is bad for security reasons. Here is the page for that.
http://www.php.net/manual/en/pdostatement.bindparam.php
You probably should look into sanitizing your user input as well. Just a heads up and unrelated to your current situation.
Also to get all the field names with PDO try this
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
Once you have all the table fields it would be pretty easy using <div> or even a <table> to arrange them as you like using a <th>
Happy learning PHP. It is fun.
Thanks guys, got it.
$table = 'tbl_gas_meters';
$result = MYSQL_QUERY("SELECT * FROM {$table}");
$fields_num = MYSQL_NUM_FIELDS($result);
ECHO "<h1>Table: {$table}</h1>";
ECHO "<table border='1'><tr>";
// printing table headers
FOR($i=0; $i<$fields_num; $i++)
{
$field = MYSQL_FETCH_FIELD($result);
ECHO "<td>{$field->name}</td>";
}
ECHO "</tr>\n";
// printing table rows
WHILE($row = MYSQL_FETCH_ROW($result))
{
ECHO "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
FOREACH($row AS $cell)
ECHO "<td>$cell</td>";
ECHO "</tr>\n";
}
while ( $row = mysql_fetch_array($field) ) {
echo $row['fieldname'];
//stuff
}
Try this :
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
while($row = mysql_fetch_assoc($field)){
echo $row['your field name here'];
}
Please note that, mysql_* functions are deprecated in new php version , so use mysqli or PDO instead.
Thanks! I adapted some of these answers to draw a table from all records from any table, without having to specify the field names. Just paste this into a .php file and change the connection info:
<?php
// Authentication detail for connection
$servername = "localhost";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxx";
$dbname = "xxxxxxxxxx";
$tablename = "xxxxxxxxxx";
$orderby = "1 DESC LIMIT 500"; // column # to sort & max # of records to display
// Create & check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); // quit
}
// Run query & verify success
$sql = "SELECT * FROM {$tablename} ORDER BY {$orderby}";
if ($result = $conn->query($sql)) {
$conn->close(); // Close table
$fields_num = $result->field_count;
$count_rows = $result->num_rows;
if ($count_rows == 0) {
die ("No data found in table: [" . $tablename . "]" ); //quit
}
} else {
$conn->close(); // Close table
die ("Error running SQL:<br>" . $sql ); //quit
}
// Start drawing table
echo "<!DOCTYPE html><html><head><title>{$tablename}</title>";
echo "<style> table, th, td { border: 1px solid black; border-collapse: collapse; }</style></head>";
echo "<body><span style='font-size:18px'>Table: <strong>{$tablename}</strong></span><br>";
echo "<span style='font-size:10px'>({$count_rows} records, {$fields_num} fields)</span><br>";
echo "<br><span style='font-size:10px'><table><tr>";
// Print table Field Names
while ($finfo = $result->fetch_field()) {
echo "<td><center><strong>{$finfo->name}</strong></center></td>";
}
echo "</tr>"; // Finished Field Names
/* Loop through records in object array */
while ($row = $result->fetch_row()) {
echo "<tr>"; // start data row
for( $i = 0; $i<$fields_num; $i++ ) {
echo "<td>{$row[$i]}</td>";
}
echo "</tr>"; // end data row
}
echo "</table>"; // End table
$result->close(); // Free result set
?>

Can't fetch information from database with urldecode

I have used urldecode to receive a member ID from a previous site. The correct ID is being displayed in the URL but I can't fetch information from the database.
members.php:
<?php
$query = "SELECT name, memberID FROM members";
if(!$result = $db->query($query)){
die('There was an error running your query[' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
printf ('<li>' . $row['name'] . '</li>');
}
?>
profiles.php:
<?php
$id = isset($_GET['memberID']);
$query = "SELECT * FROM members WHERE memberID = '".$id."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()){
printf("%s (%s)\n", $row["memberID"], $row['name']);
}
}
var_dump($query);
?>
All I get is a blank screen.
I found couple of problems in the code:
members.php
while($row = $result->fetch_assoc()){
printf ('<li>' . $row['name'] . '</li>');
}
Here you are using printf function which have 1st argument for format of string.
Correct that with echo statement as below:
while($row = $result->fetch_assoc()){
echo '<li>' . $row['name'] . '</li>';
}
profiles.php
$id = isset($_GET['memberID']);
Here you are setting the $id with isset() function return value.
You should instead set the value from GET parameter as below:
if(isset($_GET['memberID'])) $id = $_GET['memberID'];
See now if it's working.
Make sure that you use the correct capitalization of memberId vs. memberID. This is very important.
Do not pass values retrieved from GET/POST through urldecode. They already are.
Please try the following based on your code and let us know the results:
<?php
$id = isset($_GET['memberID']) ? $_GET['memberID'] : 0;
if($id > 0){
$query = "SELECT * FROM members WHERE memberID = '".$id."'";
$result = $db->query($query);
if($result){
echo "Rows found: " + $result->num_rows;
} else {
echo "No rows found";
}
} else {
echo "memberID is 0";
}
?>
Is memberID an int field in the database or a string field? If it is an int field then remove the single quotes in your query on profiles.php.

MySQL insert row from HTML table into db table

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

Categories