Unable to get simple PHP form to add/update to MyS

2019-08-22 09:03发布

问题:

I have a MySQL table with three columns; user, product, address. I am trying to get my form to either add to the table a NEW ROW OF DATA OR UPDATE a pre-existing row. My conditions for update are IF both user and product already exist, just change address. BUT IF neither exist (user and product), or just user, then append new user, product, and address info.

The form uses customer id, a dropdown box for the product, and a text box for the new address, however my SQL command for update seems to fail the page and I cannot find the error... Here is my attempt at MySQL code:

EDITED TESTED CODE - Still not working

mysqli_select_db("wp_newaddress", $con);

if(isset($_POST['submit'])) {
$id = $_POST['$userid'];
$product = $_POST['sku'];
$address = $_POST['address'];

$sql = "UPDATE wp_newaddress SET address='address' WHERE user='$userid' AND product='sku'";

echo "<p><h5>Change address:</h5>";

$loop = new WP_Query( $args );
echo '<br><select name="sku">';
    echo '<option>-- Select product--</option>';
while ( $loop->have_posts() ) : $loop->the_post();
  global $product;
    echo '<option value=' . $product->get_sku() . '>' . $product->get_sku() . ' </option>';
  endwhile;
echo '</select>';
echo '<br><input type="text" value="Insert new address here" id="address" size="40" />';
echo '<br><button type="submit" name="submit">Change address</button>';
$retval = mysqli_query( $sql, $con );
if(! $retval )
{
  die('Could not update data: ' . mysqli_error());
}
echo "Updated address successfully\n";

回答1:

Usage of mysqli_query: mysqli_query(connection,query,resultmode);. See the documentation

You have to switch $sql and $con in $retval = mysqli_query( $sql, $con );
In my opinion you also have to define $sql as string.

$sql = "UPDATE wp_newaddress SET address='address' WHERE user='$userid' AND product='sku'";


回答2:

$sql = mysqli_query("UPDATE wp_newaddress SET address='address' WHERE user='$userid' AND product='sku'");

This code executes the query.

For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure

$sql contains the above possible return values.

Thus when you try to execute the query second time in the line

$retval = mysqli_query( $sql, $con );

It is not executing the sql statement rather the return value.

For example: if the return of the first mysqli_query() is FALSE, then your second mysqli_query('FALSE', $con)

so to correct it, you will need to do

$sql = "UPDATE wp_newaddress SET address='$address' WHERE user='$userid' AND product='sku'";