MySQL INSERT statement not executed [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I cannot for the love of god figure out why this statement is not executing. When I limit it to
mysql_query("INSERT INTO my_pets() VALUES ()", $con);
it fires just fine, creating an empty row (NULL in every cell), but as soon as I give it columns and values, it refuses. See below.
Can someone point out a mistake or any other reason this (seemingly) correct code isn't firing when columns and values are specified?
Premises:
$h, $un, $pw, and $db are all fine, as I have copied it from documents that work as we speak.
There are no typos or mistakes in upper/lower case characters of column names and such.
The code:
<?php
session_start();
$h="..."; // Host name
$un="..."; // Mysql username
$pw="..."; // Mysql password
$db="..."; // Database name
$con = mysql_connect("$h", "$un", "$pw")or die("cannot connect");
mysql_select_db("$db")or die("cannot select DB");
$name = "Pip";
$gender = "F";
$species = "Dog";
mysql_query("INSERT INTO my_pets (name, gender, species) VALUES ('$name', '$gender', '$species')", $con);
mysql_close($con);
?>

Obtained from PHP Documentation, If you're using PHP 7.0.0, mysql_query will no longer work:
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
Good / Important note from someone who cares: This function should not be used for any future code and should be replaced for existing code, so I would recommend you change to PDO.

Related

How to update database using PHP variables? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
$Createdby=$_SESSION['adminlog'];
$total =$_POST['total'];
$due =$_POST['due'];
$date =$_POST['issedate'];
$invoiceno =$_POST['invno'];
$CmpnyName =$_POST['CmpnyName'];
$itemdetails =$_POST['item_details'];
$itemname =$_POST['itemname'];
$amtpaid =$_POST['paid'];
$query = "UPDATE billdata SET Total='$total' Due='$due' WHERE InvoiceNo=$invoiceno";
$result = mysql_query($query);
This is the code I am using to get HTML values to variable and update particular invoice number with new data.
First off, never use the deprecated mysql_* API.
Switch to either PDO or mysqli, both have prepared statements, which would make your code a tad bit more safe when it comes to SQL-Injections (which your code is very open for).
When a query fails, the mysql_error() global function will return the latest mysql error.
The easiest way to get information about a failing query is by adding or die(mysql_error()); after the query execution.
Example with your code:
$result = mysql_query($query) or die(mysql_error());
This will report your error and stop execute the script.
Your sql code is slightly wrong (as RST mentions), you are missing a comma between the values you are trying to set.
Using mysqli and prepared statements, your code could look something like:
// Using the mysqli object oriented style.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// Prepare the statement.
$statement = $mysqli->prepare('UPDATE billdata SET Total=?, Due=? WHERE InvoiceNo=?');
// The question marks is placeholders for the input that will be added in a while.
// Bind your parameters (ssi tells mysqli what type of params it is, s = string, i = int).
$statement->bind_param('ssi', $total, $due, $invoceno);
// Execute the statement.
$statement->execute();
// Cleanup.
$statement->close();
$mysqli->close();
$query = "UPDATE billdata SET Total='$total', Due='$due' WHERE InvoiceNo=$invoiceno";
There should be a comma between the sets of values.
It is not a good idea to use the value from $_POST() as they are, better perform some validation checks.

Displaying Random Row from SQL Database

I have been working for days now and I am at a dead end. After talking with GoDaddy support I am positive that I have the correct hostname, username/password when I run the script but it still cannot get past die().
Ultimately I am attempting to pull a single question from a database. I have combed this website but nothing i found seems to answer my question. Please help.
<?php
$hostname='localhost';
$username='username';
$password='password';
$dbname='qod';
$usertable='Questions';
$userfield='question';
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to access the Question of the Day! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = 'SELECT $.userfield FROM $.usertable ORDER BY RAND() LIMIT 1';
$result = mysql_query($query);
if($result){
while($row = mysql_fetch_array($result)){
$name = $row[$yourfield];
echo "Name: ".$name;}
}
?>
You are using dots for your SELECT variables where there shouldn't be any.
SELECT $.userfield FROM $.usertable, then calling them with:
$usertable='Questions';
$userfield='question';
Remove them from your SELECT and use proper error reporting techniques such as :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of code
and
or die('Could not connect: ' . mysql_error());
also a dollar sign in [$yourfield] for your column name; remove it also.
You should be using quotes: I.e.: ['yourfield'] - yourfield being the column name in your table that you wish to show.
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Use mysqli_* with prepared statements, or PDO with prepared statements.

PHP update MySQL table with external values

I have a mysql table that is connected to xcode via php, Im trying to update a cell using this code, and is returning nothing in the table.
<?php
$conn = mysql_connect($host, $user, $pass);
#mysql_select_db($db) or die("Unable to find database");
$routeID = $_GET["routeID"];
$newComment = $_GET["newComment"];
$query = "UPDATE routes SET comment = '$newComment' WHERE routeID='$routeID'";
mysql_query($query) or die (mysql_error("error"));
mysql_close();
?>
If I changed $routeID to routeID='routeID' or routeID=routeID it would update the entire comment column and add the actual id into it e.g. test?routeID=1
If I changed $routeID to routeID=1 or 20 etc. it would update the correct row. Any ideas on whats wrong with this.
It appears that your querystring is currently newComment=test?routeID=1, whereas it should be newComment=test&routeID=1.*
Consequently, PHP parses the current querystring as a single name newComment with the value test?routeID=1 rather than two names newComment and routeID with values test and 1 respectively.
However, please note that you absolutely must not simply concatenate values from the querystring directly into your SQL: so doing can lead to bugs if the values are not what was expected, which can be exploited by attackers to compromise your database. See How can I prevent SQL injection in PHP?
Please also note that, as documented under mysql_connect():
Warning 
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
Finally, please note that the (optional) argument to mysql_error() is the MySQL link identifier resource, $conn in your case: passing a string literal such as "error" will result in its failure.
* As documented under Data Handling, the default value for arg_separator.input (which is described as "List of separator(s) used by PHP to parse input URLs into variables.") is "&". This is consistent with the encoding used by browsers to submit form data, signified by the application/x-www-form-urlencoded MIME type.

Error: Query was empty

$nam=$_POST['name'];
$fname=$_POST['family'];
$dat=$_POST['date'];
$bal=$_POST['balance'];
$curr=$_POST['currency'];
$con=mysql_connect('localhost', 'xxxx', 'xxxx', 'xxxx');
$db=mysql_select_db('users',$con);
$ins=mysql_query("INSERT INTO users (Name, FamilyName, Date, Balance, Currency) VALUES ('$nam', '$fname', '$dat', '$bal', '$curr'))",$con);
if (!mysql_query($ins,$con))
{
die('Error: ' . mysql_error($con));
}
So guys, I got this code and I am trying to do something like a registration form. I have tripple checked the names of the variables and the query itself is working when executed in SQL database. The thing is when I include it in my php script it returns that the Query was empty. I've looked around but all errors on the Web are around not assigning to a variable or having several insert statements and so on. So my question is why am i getting this when I am actually inputting data from a web form? Error: Query was empty
P.S.
Ok so what I mde of this: I removed the check that you said was for a second time that is the if (!mysql_query($ins,$con)) { die('Error: ' . mysql_error($con)); } part now i get execution but it does not really add the entry to the database and i cannot call it. That is the new name.
You're basically trying to use mysql_query() twice:
$ins=mysql_query("INSERT INTO users (Name, FamilyName, Date, Balance,
Currency) VALUES ('$nam', '$fname', '$dat', '$bal', '$curr'))",$con);
if (!mysql_query($ins,$con))
{
$ins will contain a valid MySQL resource if the query was executed correctly, but you're attempting to use it again in the if condition.
Just remove the mysql_query() part from the condition, like so:
if(!$ins) {
# code ...
}
That should fix this particular issue. But note that your code is vulernable to SQL injection. Also, mysql_* functions are deprecated and are soon to be removed. I recommend you switch to MySQLi or PDO and start using parameterized queries to be safe.
this is incorrect
if (!mysql_query($ins,$con))
why are you performing a query of a query ??
just use if (!$ins||!$con)) if you are trying to check if the query and connection has been successful

PHP Insert into mysql

So i have php code to insert form data in a table. Here's the code:
$link = #mysql_connect("***", "***", "****");
if (!$link) {
echo "save_failed";
return;
}
mysql_select_db("***", $link);
$sql="INSERT INTO Conference (`First Name`, `Last Name`)
VALUES ('$_POST[fname]', '$_POST[lname]')";
mysql_close($link);
The *** are replaced with the actual values in the real code, obviously. But is there anything wrong with the above code? I tried to run it, it didn't have any errors with connection but it also didn't insert anything. Here's is what my mysql table looks like:
Also, I need the table to have an auto incremented number so that each entry is unique with it's own index value. Any ideas on either problem? Thanks
You haven't executed the query, which should be done as it follows:
mysql_query($sql, $link);
Also, please consider using mysqli or even better PDO as the mysql package is deprecated (see the red box), i.e. mysql_query().

Categories