Database not updating (integration in woocommerce) - php

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.

Related

How can I get the UserID of a person from a split version of their First/Last Name from FullName in PHP?

I'm trying to make a Check-in/out system.
So far I have a dropdown that get the list of active events.
<select name="events">
<?php
$conn = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
$eveny = $conn->query("select event_title from events_event where inactive=0");
while ($row=mysqli_fetch_array($eveny)) {
unset($event);
$event = $row['event_title'];
echo '<option value="'.$event.'">'.$event.'</option>';
}
?>
</select>
And a textbox that searches users based on first name, but it auto displays results (like a Google search) and then fills out the info with both First Name and Last name. Source.
The only change in the php is the echo to show both first and last names as follows:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["per_FirstName"] . " " . $row["per_LastName"] . "</p>";
}
NOW FOR THE PROBLEM
I have made the frontend into a form, and a submit button using method="post".
But something in my php is not functioning/lacking.
<?php
$db = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myname = mysqli_real_escape_string($db,$_POST['fullname']);
$eventy = mysqli_real_escape_string($db,$_POST['events']);
//$checktime = mysqli_real_escape_string($db,date("Y-m-d H:i:s"));
$evid = "SELECT event_id from events_event where event_title = '$eventy'";
$revvy = mysqli_query($db,$evid);
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
$lastName = trim($nameParts[1]);
$sql = "SELECT per_ID FROM person_per WHERE per_FirstName = '$firstName' AND per_LastName = '$lastName'";
$result = mysqli_query($db,$sql);
//$row = mysqli_fetch_row($result);
//$result = $result->fetch_all();
while($row = mysqli_fetch_assoc($result)){
$perID = $row['per_ID'];
}
while($row2 = mysqli_fetch_assoc($revvy)){
$evvy = $row['event_ID'];
}
$count = mysqli_num_rows($result);
// table row must be 1 row if it succeeded
if($count == 1) {
//session_register("myname");
//$_SESSION['login_user'] = $myname;
$checkin = "insert into event_attend (attend_id, event_id, person_id, checkin_date) values (DEFAULT, '$evvy', '$perID', now())" or die(mysqli_error());;
mysqli_query($db,$checkin);
header("location: checkedin.php");
}else {
$error = "An error occurred.";
}
}
?>
The $myname, is the result of both first name and last name, I need just First Name based on the filled out text field which uses both first and last names.
I also can't get the Event_ID from the dropdown.
If user's first and last name are separated by space:
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);

How to pull data with a link on a different page with mysqli

I figured out the way to link to the page and set what ID i would like to call:
CLICK TEST **(IS THIS RIGHT?)**
But then I need page.php to pull the id, this is what I am using at the moment to pull the id manually. How would I make the following code pull it form the link?
<?php
$query = "select * from Drinklist where id = 10";
$result = mysqli_query($conn,$query);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$List['name']." - Site Name</title>";
}
?>
I tried the following (didn't work):
$query = "select * from List where id = . $id";
Seems like I can only find the way to do it with MYSQL and not MYSQLI... Any help would be appreciated.
UPDATED CODE:
<?php
$query = "select * from Drinklist where id = ?";
$result = mysqli_prepare($conn,$query);
mysqli_stmt_bind_param($result, 'i', $_GET['id']);
mysqli_stmt_execute($result);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$Drinklist['name']." - Mixed Drinks Station</title>";
}
?>
Getting error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
object given in public_html/page.com/test/inc/drink-page.php on line 6
Ok so I ended up figuring this one out with a ton of trial and error...
Thank you chris85 for the early support and hopefully this can help you out a little. This is fun ;)
<?php
$server = "localhost";
$user = "user";
$pass = "password";
$dbname = "database";
//Creating connection for mysqli
$conn = new mysqli($server, $user, $pass, $dbname);
//Checking connection
if($conn->connect_error){
die("Connection failed:" . $conn->connect_error);
}
$article_id = $_GET['id'];
if( ! is_numeric($article_id) )
die("Looks like you are lost! <a href='#'>Back to Home</a> ");
$query = "SELECT * FROM `Whatever` WHERE `ID` =$article_id LIMIT 0 , 30";
$info = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($info, MYSQL_ASSOC))
{
$name = $Whatever['name'];
$description = $Whatever['description'];
$keywords = $Whatever['keywords'];
$lrgpic = $Whatever['lrgpic'];
$vid = $Whatever['vid'];
$name = htmlspecialchars($row['name'],ENT_QUOTES);
$description = htmlspecialchars($row['description'],ENT_QUOTES);
$keywords = htmlspecialchars($row['keywords'],ENT_QUOTES);
$lrgpic = htmlspecialchars($row['lrgpic'],ENT_QUOTES);
$vid = $row['vid']; //Use <-- to be able to have HTML in your database otherwise the above would remove <, >, /, ', ", ect.
echo "<head>";
echo "<title>$name - Site title</title>";
echo "<meta name='description' content='$description'>";
echo "<meta name='keywords' content='$keywords'>";
include 'inc/head.php'; //includes already are in a php file ;)
echo "</head>";
echo "<body>";
include 'inc/header.php';
include 'inc/nav.php';
echo "<div class='wrapper'>";
echo "<div id='drink-name'>";
echo "<h2>$name</h2>";
echo "</div>";
// AND SO ON
}
?>

php mysqli not working

I am making a chat application and this is the part that checks for new additions.
<?php
$servername = "*";
$username = "*";
$password = "****";
$dbname = "*";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
die("Connection failed: " . mysqli_connect_error($conn));
}
$id = $_GET['id'];
$sql = "SELECT position, user, comment,time FROM chat WHERE position > $id";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows() > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username=".$row['user']));
$userImage = $row2["avatar"];
echo "<div class='container-fluid well'><p class='left'>"."<img class='img-circle zoom' src='/profile_images/".
$userImage
."' style='width:32px;height:32px;'>".$row["user"]. ": " . $row["comment"]. "</p><h4><small class='right'> at ".$row['time']."</small></h4></div>";
}
}
mysqli_close($conn);
?>
it was working until I changed the line
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username=".$row['user']));
Help would be appreciated.
Update:
this is my html:
There is more. but this is the most important
<div id='newchat'></div>
<script>
$(document).ready(function(){
getChat();
var id = <?php echo $id ?>;
function getChat(){
setTimeout(getChat,1000);
$.get("getChat.php?id="+id,function( text ) {
if (text != ""){
id ++;
$( "#newchat" ).prepend( text );
}
});
}
});
</script>
Try this query :
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username='{$row['user']}'"));
Side note : Your query is unsafe. Read this
How can I prevent SQL injection in PHP?.
you forget 2 '
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE
username='".$row['user']."'"));
Simply use this query:
"SELECT * FROM login WHERE username='".$row['user']."'"
instead of
"SELECT * FROM login WHERE username=".$row['user']
and if you want a simple query then use:
$usr = $row['user'];
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM
login WHERE username=$usr"));
It'll definitely work.
Write your query as below:-
$sql = "SELECT * FROM login WHERE username='{$row['user']}'";
mysqli_fetch_assoc(mysqli_query($conn,$sql));
Hope it will help you :)

How do I retrieve a single row from a table using PHP?

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

PHP/MySQL Problem

Why does this only print the sites specific content under the first site, and doesn't do it for the other 2?
<?php
echo 'NPSIN Data will be here soon!';
// connect to DB
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to DB');
$dbname = 'npsin';
mysql_select_db($dbname);
// get number of sites
$query = 'select count(*) from sites';
$result = mysql_query($query) or die ('Query failed: ' . mysql_error());
$resultArray = mysql_fetch_array($result);
$numSites = $resultArray[0];
echo "<br><br>";
// get all sites
$query = 'select site_name from sites';
$result = mysql_query($query);
// get site content
$query2 = 'select content_name, site_id from content';
$result2 = mysql_query($query2);
// get site files
// print info
$count = 1;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "Site $count: ";
echo "$row[0]";
echo "<br>";
$contentCount = 1;
while ($row2 = mysql_fetch_array($result2, MYSQL_NUM)) {
$id = $row2[1];
if ($id == ($count - 1)) {
echo "Content $contentCount: ";
echo "$row2[0]";
echo "<br>";
}
$contentCount++;
}
$count++;
}
?>
The problem is that you assume that once your finished looking for the row with the same id as the site row, that it'll reset the $result2 query to the beginning. This means that after you find your first row (unless you were to sort the two queries), that the second pass of the while loop wouldn't have any results left. You should consider caching the inner while loop first and then using an array lookup to get the value.
An even better solution would involve a join from sites to content which wouldn't require this complex matching process. Joins are a VERY important part of SQL, I highly suggest learning how to use them. http://dev.mysql.com/doc/refman/5.0/en/join.html

Categories