rn10950
rn10950

Reputation: 93

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?

<?php
 //POST VARIABLES------------------------------------------------------------------------
   //$rawcode = $_POST[ 'editor1' ];
   //$code = mysqli_real_escape_string($rawcode);
   $code = 'GOOD';
   $id = "1";
   echo "$code"; 
 //SQL VARIABLES-------------------------------------------------------------------------
   $database = mysqli_connect("localhost" , "root" , "password" , "database");
 //INSERT QUERY DATA HERE----------------------------------------------------------------
   $queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
   mysqli_query($queryw, $database);
 //REDIRECT TO LOGIN PAGE----------------------------------------------------------------
   echo "<script type='text/javascript'>\n";
   echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
   echo "</script>";
?>

Upvotes: 0

Views: 155

Answers (1)

Kai Qing
Kai Qing

Reputation: 18843

Your problem is that mysql INSERT does not support WHERE. Change the query to:

INSERT INTO users (code) VALUES ('$code')

Then to update a record, use

UPDATE users SET code = '$code' WHERE id = $id

Of course, properly prepare the statements.

Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here: http://php.net/manual/en/mysqli.query.php

It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Upvotes: 4

Related Questions