I've created a table and stored values in it. The table has a column 'ID' which is unique.
Now I’ve created a form where there is a button marked Retrieve. When I enter the ID and click the Retrieve button, I want to view the data corresponding to this ID.
How do I do this using PHP and MYSQL?
I’ve got some code below, but it isn‘t working. No error message is being showed. But there is no problem with the db connection. Rest of the functions working except for 'RETRIEVE'.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".'$id'."";
$dis = $db->query($retrieve);
$row = $dis->fetch_assoc();
echo 'Details are: '.$row['id'];
}
}
$conn->close();
?>
Change sql select clause into this:
"SELECT * FROM ins WHERE Id = " .$id. " LIMIT 1";
$retrieve = "SELECT * FROM ins WHERE Id = ".$id." LIMIT 1";
The limit will work for you
In the SQL statement ($retrieve), the single quotes are killing it for you. Try either of the following:
Remove the single quotes around $id and keep the rest of the statement the same
Change '$id' to "'{$id}'" (if you're keen on getting the single quotes around the $id value - just in case $id is a text value and not a number)
Try this
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
$dis = $db->query($retrieve);
$row = $dis->fetch_row();
Related
Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
I'm trying to make something which will only display the name of the row which has ID 1 but I can't seem to get it to work. I can make it display all the names but I only want it to display the name of user ID 1. This is my current code but it doesn't work.
<a style="font-size: 17px; color: #ff0000;"><?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result=mysqli_query($q);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row != FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo $name;
} else{echo "it's false :(";};
?></a>
It returns:
it's false :(
you may need the while() check on there.
Try something like:
Your database connection:
$servername = "YOUR_HOST";
$username = "YOUR_USER";
$password = "YOUR_PASSWORD";
$dbname = "YOUR_DATABASE";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then your main file with displaying the row you want:
// create query
$q = "SELECT * FROM Team WHERE id = 1";
// get the records from the database
if ($result = $mysqli->query($q))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// fetch the results
while ($row = $result->fetch_object())
{
$name = $row->name;
echo $name;
}
}
else
{
echo "No results to display!<br><hr><br>";
}
}
else
{ // show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
mysqli_query requires first parameter should be connection string and second is the query
mysqli_query($link, "your query");
Ref: http://php.net/manual/en/mysqli.query.php
You need to add the Connection-Parameter!
$result=mysqli_query($db, $q);
instead of
$result=mysqli_query($q);
I just migrated a site from one domain to another domain (and another host). I made sure that all links were replaced and exported/imported my database. The migration seemed to have worked, but for some reason I am getting an error on my new domain that I did not get on my old domain (with, as far as I know, the same code).
My error is: "Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, null given in path on line 84". I looked at the other StackOverflow questions that address this error, but I have not found a solution yet.
This is my code:
<?php
session_start();
// 1. Create a database connection
$dbhost =
$dbuser =
$dbpass =
$dbname =
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occurred.
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
// 2. Perform database query
if (empty($_SESSION['order'])) {
$query = "INSERT INTO `orders` (`order_id`) VALUES (NULL)";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// 3. Use returned data (if any)
$order_id_recent = mysqli_insert_id($connection);
$_SESSION['order'] = $order_id_recent;
}
$size = $_POST["size"];
$paper = $_POST["paper"];
$type = $_POST["type"];
$quantity = $_POST["quantity"];
// 2. Perform database query
$query2 = "SELECT product_id FROM product WHERE product_type = '$type' AND size = '$size' AND paper = '$paper'";
$result2 = mysqli_query($connection, $query2);
// Test if there was a query error
if (!$result2) {
die("Database query failed.");
}
// 3. Use returned data (if any)
while($row = mysqli_fetch_assoc($result2)) {
$product_id = $row['product_id'];
}
$order_id = $_SESSION['order'];
// 2. Perform database query
$order_id = $_SESSION['order'];
$query3 = "SELECT * FROM order_item WHERE order_id = '$order_id' AND product_id = '$product_id'";
$result3 = mysqli_query($connection, $query3);
// Test if there was a query error
if (!$result3) {
die("Database query failed.");
}
while($row = mysqli_fetch_assoc($result3)) {
$itemexistrows = mysqli_num_rows($result3);
}
if ($itemexistrows > 0) {
$query4 = "UPDATE order_item SET quantity = quantity + '$quantity' WHERE product_id = '$product_id' AND order_id = '$order_id'";
$result4 = mysqli_query($connection, $query4);
if (!$result4) {
die("Database query failed.");
} else {
echo 'The item has been added to your cart. <a class="text-red" href="viewcart.php">View your cart</a></div>.';
}
} else {
$query5 = "INSERT INTO `order_item`(`order_item_id`, `product_id`, `quantity`,`order_id`) VALUES (NULL,'$product_id','$quantity','$order_id')";
$result5 = mysqli_query($connection, $query5);
if (!$result5) {
die("Database query failed.");
} else {
echo 'The item has been added to your cart. <a class="text-red" href="viewcart.php">View your cart</a></div>.';
}
}
// 4. Release returned data
mysqli_free_result($result);
// 5. Close database connection
mysqli_close($connection);
?>
The weird thing is that my website still seems to work. These lines of code are part of a shopping cart module and the shopping cart seems to get updated.
I suspect that $_SESSION['order'] is not empty and thus $result is not set as it does not seem to be addressed inside the same if statement.
The following would almost certainly make the problem go away.
if(isset($result) && $result!=null){
// 4. Release returned data
mysqli_free_result($result);
}
Or, as suggested in comments, and probably better:
if(isset($result) && is_resource($result)){
// 4. Release returned data
mysqli_free_result($result);
}
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
This code is not working although it's correct
I am using object oriented php.
$this->id is a variable passed by link from another page.
When I run the code it tells me it was successful but that there are zero affected rows.
The one line above is part of the following code:
<?php
class edit {
private $status;
private $remain;
private $cost;
private $id;
public function edit_data() {
$this->status = strtoupper(strip_tags($_POST['status']));
$this->remain = strip_tags($_POST['remain']);
$this->cost = strip_tags($_POST['cost']);
$submit = $_POST['submit'];
$this->id = $_GET['edit'];
$con = mysql_connect("localhost","root","")
or die("Failed to connect to the server: " . mysql_error());
mysql_select_db("Users")
or die("Failed to connect to the database: " . mysql_error());
if($submit) {
if($this->status and $this->remain and $this->cost) {
$sql = "UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
$query = mysql_query($sql,$con);
if(!$query) {
echo("Could not update data: " . mysql_error());
}
echo "<h4>Customer reservation data has been updated successfully.</h4>";
echo "Number of affected rows: " . mysql_affected_rows();
}
else {
echo "Please fill in all fields.";
}
}
mysql_close($con);
}
}
$edit = new edit();
echo $edit->edit_data();
?>
Are you sure about your concatenation?
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
Print $sql to see the value.
If your database is already updated, you will receive 0 affected lines.
I am not totally sure but try this,
"UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
It seems that your table doesn't contain a value which satisfies where condition.
You can check this by executing a simple query.
$sql = "select * from reservations where id='$this->id'";
I am using Wordpress / WooCommerce. My client doesn't want users to have to create an account to buy something, but still wants to store the customer address so it auto populates when the user comes back to the site for a future purpose.
I had a school project where I saved a note to a database (plain text in a textbox). It grabs the "notes" already in the database, and shows them to you, with an option to update the note. This updates the database entry.
I am trying to adapt this code to work with woocommerce. I haven't changed much besides the name of the table.
The database connects fine, and it pulls the content from the table as requested.
My issue is: the database is not updating the entry when I click "update". I'm not sure if this is because I'm trying to use it within woocommerce, and the shopping cart is causing issues? But it's practically the same code as my working school project.
You can see it working here (once you add something to your cart): http://www.onelifehealthycuisine.com/mobile/checkout/
Currently, I'm just trying to get it to update the address, once that works I'll add in the other cell's to update.
Database
Name: tbl_stored_address
| ID | ip_address | address | city | province | postal |
Test Entry: 2, 96.48.1.29, 123 fake street, vancouver, bc, v3c 5r6
function dbConnect(){
$db_host = 'xxx.xxx.com';
$db_un = 'xxxx';
$db_pass = 'xxxx';
$db_name = 'xxxx';
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8",$db_un,$db_pass);
mysql_connect($db_host, $db_un, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
}
dbConnect();
function getAddys(){
$user_id = '96.48.1.29'; //get user IP
$query = "SELECT tbl_stored_address.address, tbl_stored_address.id FROM tbl_stored_address WHERE tbl_stored_address.ip_address ='".$user_id."';";
$result = mysql_query($query) or die(mysql_error());
//saves number of rows returned
$rowCount = mysql_num_rows($result);
echo "<form enctype='multipart/form-data' action='form-checkout.php' method='post'>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<textarea name='address".$row['id']."' id='address".$row['id']."'>".$row['address']."</textarea><br/>";
}
echo "<br/><input type='submit' value='Update Note(s)' name='updateNote'/><br/>";
echo "</form>";
}
//this will check if the user clicked on "update" for a note, and then update the correct notes using the ID
if(isset($_POST['updateNote']))
{
$user_id = '96.48.1.29'; //get user IP
$query = "SELECT tbl_stored_address.id FROM tbl_stored_address WHERE tbl_stored_address.ip_address ='".$user_id."';";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if((isset($_POST['address'.$row['id'].'']))){
$value = $_POST['address'.$row['id'].''];
$theID = $row['id'];
$query2 = "UPDATE tbl_stored_address SET tbl_stored_address.address='".mysql_real_escape_string($value)."' WHERE tbl_stored_address.id ='".$theID."';";
$result2 = mysql_query($query2) or die(mysql_error());
}
}
}
?>
<h2>Delivery Address</h2><br/><br/>
<?php getAddys(); ?>
****UPDATE****
I've tried adding the code to a page without woocommerce and accessing the the PHP page directly, and it updates the database fine: http://www.onelifehealthycuisine.com/mobile/wp-content/themes/onelife/page-test.php
So is it the fact that the URL doesn't end with a .php file? Or something in the woocommerce template not allowing me to run the form properly? I can't seem to figure it out.
Assuming tbl_stored_address.id is an int, this :
WHERE tbl_stored_address.id ='".$theID."'
won't match anything. Use
WHERE tbl_stored_address.id =".$theID."
That being said, you shouldn't using the mysql_ functions, and DEFINITELY should not be building your query using string concatenation. That being said, this is your script updated to use the MySQLi extension:
<?php
function dbConnect()
{
$db_host = 'xxx.xxx.com';
$db_un = 'xxxx';
$db_pass = 'xxxx';
$db_name = 'xxxx';
$conn = mysqli_connect($db_host, $db_un, $db_pass, $db_name) or die(mysqli_error());
}
dbConnect();
function getAddys()
{
$user_id = '96.48.1.29'; //get user IP
$query = "SELECT tbl_stored_address.address, tbl_stored_address.id FROM tbl_stored_address WHERE tbl_stored_address.ip_address = '" . $user_id . "';";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
//saves number of rows returned
$rowCount = mysqli_num_rows($conn, $result);
echo "<form enctype='multipart/form-data' action='form-checkout.php' method='post'>";
while ($row = mysqli_fetch_assoc($conn, $result))
{
echo "<textarea name='address".$row['id']."' id='address" . $row['id'] . "'>" . $row['address'] . "</textarea><br/>";
}
echo "<br/><input type='submit' value='Update Note(s)' name='updateNote'/><br/>";
echo "</form>";
}
//this will check if the user clicked on "update" for a note, and then update the correct notes using the ID
if(isset($_POST['updateNote']))
{
$user_id = '96.48.1.29'; //get user IP
$query = "SELECT tbl_stored_address.id FROM tbl_stored_address WHERE tbl_stored_address.ip_address = '" . $user_id . "';";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($conn, $result))
{
if((isset($_POST['address' . $row['id']])))
{
$value = $_POST['address' . $row['id']];
$theID = $row['id'];
$query2 = "UPDATE tbl_stored_address SET tbl_stored_address.address = '" . mysqli_real_escape_string($conn, $value) . "' WHERE tbl_stored_address.id = " . $theID . ";";
$result2 = mysqli_query($conn, $query2) or die(mysqli_error($conn));
}
}
}
?>
<h2>Delivery Address</h2><br /><br />
<?php getAddys(); ?>
The MySQLi extensions reverse the order of the parameters from what you may be used to, with the connection being the first parameter. Like the MySQL extension, if you omit the connection object, the extension functions will attempt to reuse an existing open connection.
Since we really don't want to use string concatenation in our SQL, you need to get familiar with using prepared statements, which the MySQli extension supports. Here's your code with prepared statements:
<?php
function dbConnect()
{
$db_host = 'xxx.xxx.com';
$db_un = 'xxxx';
$db_pass = 'xxxx';
$db_name = 'xxxx';
$conn = mysqli_connect($db_host, $db_un, $db_pass, $db_name) or die(mysqli_error());
}
dbConnect();
function getAddys()
{
$user_id = '96.48.1.29'; //get user IP
if ($query = mysqli_prepare($conn, "SELECT tbl_stored_address.address, tbl_stored_address.id FROM tbl_stored_address WHERE tbl_stored_address.ip_address = ?;"))
{
mysqli_stmt_bind_param($query, "s", $user_id); # 's' indicates that this parameter is a string
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $row);
echo "<form enctype='multipart/form-data' action='form-checkout.php' method='post'>";
while (mysqli_stmt_fetch(($query))
{
echo "<textarea name='address" . $row['id'] . "' id='address" . $row['id'] . "'>" . $row['address'] . "</textarea><br/>";
}
echo "<br/><input type='submit' value='Update Note(s)' name='updateNote'/><br/>";
echo "</form>";
mysqli_stmt_close($query);
}
}
//this will check if the user clicked on "update" for a note, and then update the correct notes using the ID
if(isset($_POST['updateNote']))
{
$user_id = '96.48.1.29'; //get user IP
if ($query = mysqli_prepare($conn, "SELECT tbl_stored_address.address, tbl_stored_address.id FROM tbl_stored_address WHERE tbl_stored_address.ip_address = ?;"))
{
mysqli_stmt_bind_param($query, "s", $user_id); # 's' indicates that this parameter is a string
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $row);
while (mysqli_stmt_fetch(($query))
{
if((isset($_POST['address' . $row['id']])))
{
$value = $_POST['address' . $row['id']];
$theID = $row['id'];
if ($updateQuery = mysqli_prepare($conn, "UPDATE tbl_stored_address SET tbl_stored_address.address = ? WHERE tbl_stored_address.id = ?;"))
{
$updateQuery = "UPDATE tbl_stored_address SET tbl_stored_address.address = ? WHERE tbl_stored_address.id = ?;";
mysqli_stmt_bind_param($updateQuery, "s", $value); # 's' indicates that this parameter is a string
mysqli_stmt_bind_param($updateQuery, "i", $theID); # 'i' indicates that this parameter is an integer
mysqli_stmt_execute($updateQuery);
}
}
}
mysqli_stmt_close($query);
}
}
?>
<h2>Delivery Address</h2><br /><br />
<?php getAddys(); ?>
There may be errors in the code above, so caveat emptor.
You can find everything you need to learn the MySQLi extension on the PHP.net website: http://php.net/manual/en/book.mysqli.php. You'll also find the docs for PDO, which was the last extension I used when coding in PHP.