not updating the sql database - php

i wrote the following code,but its not updating the database,,its a part of a script and it cease to work..cant find a way around it .. need suggestions
<?php
$link = mysql_connect('xxxxxxxx');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
echo $usernames;
$update = "INSERT sanjana SET $name ='$usernames'";
mysql_query($update, $link);
$update1 = "INSERT INTO sanjana (name)VALUES ($usernames)";
mysql_query($update1, $link);
?>

$update = "INSERT sanjana SET $name ='$usernames'";
this probably is meant as an UPDATE statement, so for an update it should be
$update = "UPDATE sanjana set name = '$usernames'";
I put name and not $name due to your second query and not seeing $name being defined anywhere. Be aware that this will change the value in the column name of every row in the sanjana table to the value of $usernames, normally a statement such as this gets limited by conditions, e.g. WHERE userid = 33
$update1 = "INSERT INTO sanjana (name) VALUES ($usernames)";
for an INSERT statement it needs to have the values quoted so
$update1 = "INSERT INTO sanjana (name) VALUES ('$usernames')";
Be wary that this way of putting variables directly into your query string makes you vulnerable to SQL injection, to combat this please use the PDO or mysqli extensions, they both protect you from injection by providing you with prepared statements ; plain old mysql_* is not recommended for use anymore.
using pdo you'd use prepared statements like this
<?php
// we got $usernames from wherever you define it
$pdo = new PDO('mysql:dbname=mydb;host=localhost','username','password');
// to insert
$statement = $pdo->prepare('INSERT INTO `sanjana` (name) VALUES (:name)');
// the following replaces :name with $usernames in a safe manner, defeating sql injection
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
// to update
$statement = $pdo->prepare('UPDATE `sanjan` SET `name` = :name');
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
so as you can see protecting your code from malicious input is not hard and it even makes your SQL statements a lot easier to read. Did you notice that you didn't even need to quote your values in the SQL statement anymore? Prepared statements take care of that for you! One less way to have an error in your code.
Please do read up on it, it will save you headaches. PDO even has the advantage that it's database independent, making it easier to use another database with existing code.

The right update sql clause is like so:
UPDATE table
SET column = expression;
OR
UPDATE table
SET column = expression
WHERE predicates;
SQL: UPDATE Statement
Your query should be like this:
$update = "UPDATE sanjana SET $name ='$usernames'";
mysql_query($update, $link);
Of course you need to specify a row to update (id), other wise, the whole table will set column $name to $usernames.
UPDATE:
Because you are inserting a data in empty table, you should first execute $update1 query then execute $update query. UPDATE clause will make no change/insert on empty table.

Problem 1: use the correct "insert into" (create new record) vs. "update" (modify existing record)
Problem 2: It's good practice to create your SQL string before you call mysql_query(), so you can print it out for debugging
Problem 3: It's also good practice to detect errors
EXAMPLE:
<?php
$link = mysql_connect('xxxxxxxx')
or die('Could not connect: ' . mysql_error());
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
$sql = "INSERT INTO sanjana (name) VALUES ('" . $usernames + ")";
echo "sql: " . $sql . "...<br/>\n";
mysql_query($sql, $link)
or die(mysql_error());

You have INSERT keyword for your update SQL, this should be changed to UPDATE:
$update = "UPDATE sanjana SET $name ='$usernames'";

Related

Query not inserting data

trying to submit data from a form but does not seem to be working. Can't spot any problems?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proId = $_POST["id"];
$proCode = $_POST["code"];
$proDescr = $_POST["descr"];
$proManu = $_POST["manu"];
$proCPU = $_POST["cpu"];
$proWPU = $_POST["wpu"];
$proBarCode = $_POST["barcode"];
$proIngredients = $_POST["ingredients"];
$proAllergens = $_POST["allergenscon"];
$proMayAllergens = $_POST["allergensmay"];
//Insert users data in database
$sql = "INSERT INTO prototype.Simplex_List (id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay)
VALUES ('$proId' , '$proCode', '$proDescr' , '$proManu' , '$proCPU' , '$proWPU' , '$proBarCode' , '$proIngredients' , '$proAllergens' , '$proMayAllergens')";
//Run the insert query
mysql_query($sql)
First and foremost, please do not use mysql_*** functions and please use prepared statements with
PDO http://php.net/manual/en/pdo.prepare.php
or mysqli http://php.net/manual/en/mysqli.quickstart.prepared-statements.php instead. Prepared statements help protect you against sql injection attempts by disconnecting the user submitted data from the query to the database.
You may want to try using mysql_real_escape_string http://php.net/manual/en/function.mysql-real-escape-string.php to ensure no stray " or ' is breaking your query.
$proId = mysql_real_escape_string($_POST["id"]);
$proCode = mysql_real_escape_string($_POST["code"]);
$proDescr = mysql_real_escape_string($_POST["descr"]);
$proManu = mysql_real_escape_string($_POST["manu"]);
$proCPU = mysql_real_escape_string($_POST["cpu"]);
$proWPU = mysql_real_escape_string($_POST["wpu"]);
$proBarCode = mysql_real_escape_string($_POST["barcode"]);
$proIngredients = mysql_real_escape_string($_POST["ingredients"]);
$proAllergens = mysql_real_escape_string($_POST["allergenscon"]);
$proMayAllergens = mysql_real_escape_string($_POST["allergensmay"]);
Additionally ensure your form is being submitted by calling var_dump($_POST) to validate the data
You can also see if the query is erroring by using mysql_error http://php.net/manual/en/function.mysql-error.php
if (!mysql_query($sql)) {
echo mysql_error();
}
advices about PDO, prepared statements were done.
1) Do you have a database and connection to it?
Look at your prototypeconnect.php and find database name there. check that its name and password is similar that u have.
2) Do you have a table named prototype.Simplex_List in your database?
a) IF YOU HAVE:
check if your mysql version >= 5.1.6
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
b) IF YOU HAVE BUT ITS NAME is Simplex_List:
b-1) if your database name IS NOT prototype:
replace your
$sql = "INSERT INTO prototype.Simplex_List
with
$sql = "INSERT INTO Simplex_List
b-2) if your database name IS prototype:
you should escape your $_POST data with mysql_real_escape_string as #fyrye said.
c) IF YOU HAVE NOT:
you should create it
3) Check your table structure
does it have all theese fields id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay?
if you have there PRIMARY or UNIQUE keys you should be sure you are not inserting duplicate data on them
but anyway replace your
$sql = "INSERT INTO
with
$sql = "INSERT IGNORE INTO
PS: its not possible to help you without any error messages from your side

How to grab an auto incremented variable and insert it into an insert query

I am trying to do a couple of php insert queries into a relational database, but I am running into a bit of an issue. In order for this relation to work I need to grab the autoincremented value from the first query and then insert it into the second query so the relation between the two exists.
I have this:
$query2 = "INSERT into words values ('' ,'$name') ";
-- The first value listed as '' is the auto-incremented primary key --
$query3 = "INSERT into synonyms values ('' , '', $alias') ";
-- The first value listed is the auto incremented pk, the second value needs to be the fk or the pk from the first query, but I don't know how to place it there. --
Is there a way to do this? Any help would be appreciated.
Here an SQL Fiddle to help y'all out:
http://sqlfiddle.com/#!2/47d42
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO words(word) values ('word1')");
$last_id = mysql_insert_id();
mysql_query("INSERT INTO words(synonym_id,synonym) values ($last_id, "synonym1)");
?>
Reference: http://php.net/manual/en/function.mysql-insert-id.php
. . You should consider using PDO in most recent PHP versions for its modern features, such as prepared statements, so that you don't need to worry about SQL Injection or broken escaping functions.
. . Using transactions is also advisable if the follow up queries are mandatory for the record to be useful. Using transactions keeps your database clear of the garbage of any failed second or third queries.
. . Also, you can omit the Auto-Increment field when running the Insert Query if you list the other fields after the table name. I think it's a much more common pattern, like INSERT INTO table (field1, field2) VALUES ("value1", "value2"). I used it in the example below:
$pdo = new PDO('mysql:host=localhost;dbname=database', 'user', 'pass');
$pdo->beginTransaction();
try {
$prepared = $dbh->prepare('INSERT INTO words (fieldName) values (?)');
$prepared->execute(array($name));
$fID = $pdo->lastInsertId();
$prepared = $dbo->prepare('INSERT INTO synonyms (fieldName) Values (?, ?)';
$prepared->execute(array($fID, $alias));
$dbo->commit();
} catch(PDOExecption $e) {
$dbo->rollback();
print 'Error: '. $e->getMessage();
}
. . Note that this will not work with MSSQL as it doesn't support "lastInsertId".
. . Amplexos.
not sure if you're using MySQL native functions or not. If so the answer is to use mysql_last_id(). These functions are deprecated and are not adivsable to use.
EXAMPLE:
//escape your indata
$brand= mysql_real_escape_string($_POST['brand']);
$sql = "INSERT INTO cars(brand) VALUES('{$brand}')";
mysql_query($sql);
//find last id from query above
$id = mysql_last_id();
Try PDO instead:
PDO::lastInsertId
EXAMPLE:
$brand= $_POST['brand'];
$sql = "INSERT INTO cars(brand) VALUES (:brand)";
$query = $conn->prepare($sql);
$query ->execute(array(':brand'=>$brand));
$id = $conn->lastInsertId();
http://www.php.net/manual/en/book.pdo.php

Php update function

I wrote this code
if(isset($_POST['update'])) {
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
$sql=("UPDATE settings (name, meta, description) VALUES ('$webname', '$webmeta', '$webdesc')");
}
but the problem is that it doesn't update my database, and I cannot find anything wrong in the code ...
I have name "update" on submit button, and all my fields are the same as in code
That's insert! Not update!
$sql=("UPDATE `settings` SET `name` = '$webname',
`meta` = '$webmeta',
`description` = '$webdesc')
WHERE [some condition]");
And replace the [some condition] with a valid condition.
Your code is heavily vulnerable to SQL Injection.
Consider escaping the input by replacing these:
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
With:
$webname = mysql_real_escape_string($_POST['webname']);
$webmeta = mysql_real_escape_string($_POST['webmeta']);
$webdesc = mysql_real_escape_string($_POST['webdesc']);
Or something equivalent like PDO or MySQLi.
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
u need to first formulate query ans then run/ execute that
$query = "UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value";
// Perform Query
$result = mysql_query($query);
You need to run
$connection = mysql_connect($server, $serv_Username, $serv_Password);
mysql_select_db($dbase_name, $connection);
mysql_query($update_query, $connection));
I don't know if this is your problem (don't know how much you know about PHP so just saying).
Also your syntax is wrong. Should be:
UPDATE tablename SET column_name='some_value' WHERE column_name ='some_value'
note that this is diffrent from mentioned above without the thingys covering the column_name parameters.
better is to use PDO as mentioned above, mysql_ can be used "safely" on < PHP 5.5.
Try The code shown below
Just replace the field names and values with your information on your database
$editid=$_POST['editid'];
$username=callback($_POST['username']);
$password=callback($_POST['password']);
$name=callback($_POST['name']);
$age=callback($_POST['age']);
$phone=callback($_POST['phone']);
$emailaddress=callback($_POST['emailaddress']);
$gender=callback($_POST['gender']);
$description=callback($_POST['description']);
$update=update("users","username='".$username."',password='".$password."',name='".$name."',age='".$age."',phone='".$phone."',emailaddress='".$emailaddress."',gender='".$gender."',description='".$description."' ","ID='".$editid."' " );

php query to insert string into database

<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.

SQL error in php

Hey, I wrote some code for extracting some information out of the database and checking to see if it met the $_COOKIE data. But I am getting the error message:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
My code so far is:
$con = mysql_connect("XXXX","XXXXX","XXXXXXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXXXXX", $con);
$id = $_COOKIE['id'];
$ends = $_COOKIE['ends'];
$userid = strtolower($_SESSION['username']);
$queryString = $_GET['information_from_http_address'];
$query = "SELECT * FROM XXXXX";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
if ($queryString == $row["orderid"]){
$sql="UPDATE members SET orderid = ''WHERE (id = $id)";
$sql="UPDATE members SET level = 'X'WHERE (id = $id)";
$sql="UPDATE members SET payment = 'XXXX'WHERE (id = $id)";
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
}
Any help would be appreciated,
Thanks.
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
should be
$sql="UPDATE members SET ends = '$ends'WHERE (id = '$id')";
(IE add the ' around $id)
I'm not sure if this is the error, but do you realize you're code only runs the last UPDATE? You're assigning $sql 4 time, and only running it after the fourth assignement...
If $_COOKIE['id'] does not have a value, then $id in your SQL statements will be blank, leaving your SQL looking like this:
UPDATE members SET ends = 'something' WHERE (id = )
which, of course, is invalid SQL.
Only one of the SQL statements will execute, and that's the last one. You need to add some whitespace before the WHERE clause, like this:
$sql="UPDATE members SET ends = '$ends' WHERE (id = $id)";
Also be wary of SQL injection attacks in the event that your cookie is altered by the end user. One other thing of note is your orderid column. Is it a VARCHAR or some other unique identifier? If it's an integer, then setting it to empty string will not work. You might want to rethink your schema a bit here.
EDIT: Another thing you need to do is check to make sure the cookies actually have values. If not, your SQL strings will be messed up. Have you though about using parameterized queries through PDO so you don't have to worry about SQL injection at all?
first of all you keep overwriting $sql variable so only the
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
is being executed.
And I would say that $id variable is not what you think it is (maybe empty as query like the one above without id:
$sql="UPDATE members SET ends = '$ends'WHERE (id = )";
would throw such error back.
Try
$id = NULL;
before
$id = $_COOKIE['id'];
if the error is gone that means that $id is not what you think it is

Categories