Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm sure it's a kickself-obvious typo, but I can't see it. I'm trying to INSERT data taken from a HTML form using POST into a MySQL database using PHP. The POST works successfully, but the query fails; I've checked the table to make sure nothing new has been inserted.
Here's the PHP code intended to run the query:
if ($_POST) {
$username = "root";
$password = "root"; //ssh don't tell
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$dbname = "asoiaf";
$tablename = "charlist";
$id = '3';
$bookIntroduced = $_POST['bookIntroduced'];
$pageIntroduced = $_POST['pageIntroduced'];
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$oldSurname = $_POST['oldSurname'];
$alias = $_POST['alias'];
$title = $_POST['title'];
$pageIntroduced = $_POST['regnalNumber'];
// Below is the query that fails to execute.
$query = "INSERT INTO $tablename (
$id, $bookIntroduced, $pageIntroduced, $title, $forename, $surname, $oldSurname, $alias, $regnalNumber
)";
mysql_query($query) or die("Nah, I don't feel like being helpful.");
mysql_close($dbhandle);
}
And here is the structure of the table given by the DESCRIBE command:
Can anyone help me to identify the problem?
Also, if it wasn't clear, I'm new to PHP and SQL.
Doing a SQL query like this is bad practice in many ways, not least because it's extremely fragile and insecure, but I think it will work if you add VALUES and quote the strings.
$query = "INSERT INTO $tablename VALUES (
'$id', '$bookIntroduced', '$pageIntroduced', '$title', '$forename', '$surname', '$oldSurname', '$alias', '$regnalNumber'
)";
I advise against doing this though, and I'm giving this answer just because it's the shortest path to working code. Always name your table and columns (INSERT INTO mytable (col1, col2) VALUES (:val1, :val2)), and use prepared statements with mysqli.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
here's a part of my code that AFTER you submit your login credentials checks your username, password, etc...:
mysql_select_db("robur_mike") or die ("Could not find DB!");
$query = mysql_query("SELECT * FROM Bx1_Users WHERE Username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
while ($row =mysql_fetch_assoc($query))
{
$dbusername = $row['Username'];
$dbpassword = $row['Password'];
$dbfirstname = $row['FirstName'];
$dblastname = $row['LastName'];
}
.....
I now need to "translate" that to run under a DB2 database in BlueMix. I am already connected to the database using the code provided here:
How to connect to a SQL Database-s2 from a .php application in BlueMix
The query should be OK since it is basic SQL. What you should change is the way you run it, since in your old code you are using the mysql library.
Looking at the other question, I assume that you are able to connect doing something like:
$conn = db2_connect($conn_string, '', '');
Now to execute the query you can use db2_exec 'translating' your code to something like:
$sql = "SELECT * FROM <schemaName>.Bx1_Users WHERE Username='$username'";
if ($conn) {
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_assoc($stmt)) {
$dbusername = $row['Username'];
$dbpassword = $row['Password'];
$dbfirstname = $row['FirstName'];
$dblastname = $row['LastName'];
}
}
db2_close($conn);
As you can see I've added a placeholder for the schema name in the SQL query. You can retrieve it within your SQL Database dashboard (Manage/Work with tables).
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I try to learn mysql an have a problem with a sql query.
i made a database connection with mysqli
the php script create a table code_scanned in database.
Creating the Table works very good!
But my second query to fill the table wont work :(
If i paste the query manually to phpadmin it works.
But not in my php script.
Can please anyone have a look on my code, what i do wrong.
$servername = "xxxxxxx";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "xxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS code_scanned (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
produkt VARCHAR(50) NOT NULL,
code VARCHAR(30) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "code_scanned erstellt";
} else {
echo "Fehler" . $conn->error;
}
$sql = "INSERT INTO code_scanned (produkt, code) VALUES ('gates', 'Microsoft')";
$conn->close();
Exexute the insert query :
And correct The code:
$sql = "INSERT INTO code_scanned (produkt, code) VALUES ('gates', 'Microsoft')";
$result= mysqli_query($conn,$sql);
if($result)
{
echo "Insert sucessfully";
}
else
{
echo("Sorry:".mysqli_errno($conn));
}
$conn->close();
You are not running the second query. Put this below the line that has $sql = "INSERT...."
$conn->query($sql);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to insert item into my database, but it seems cannot insert into it, here is my code, anyone know the reason ?
after the submission, I check my table 'info', it also nothing changed.
http://i.stack.imgur.com/z9rxI.jpg
this is the front-end of signup page, and the test.php after the submission
You do not have ' wrapped around your key accessors on your $_POST variables that you pass directly to the query function (which you shouldn't...see below). However instead of showing you how to correct that, I will instead show you how to secure yourself from SQL injection a bit better.
As it stands, you're super vulnerable to SQL injection by simply allowing the user to post data directly to your database. Instead use a prepared statement to combat this particular case.
$stmt = $mysqli->prepare('INSERT INTO info(username, password, first_name, last_name, location, email, pwv) VALUES(?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss',
$_POST['username'],
$_POST['password'],
$_POST['firstname'],
$_POST['lastname'],
$_POST['location'],
$_POST['email'],
$_POST['pwv']);
$stmt->execute();
$stmt->store_result();
if( count( $stmt->num_rows ) > 0 ) {
//this is success
}
Set your $_POST to variables:
$username = $_POST['username'];
$password = $_POST['password'];
$last_name = $_POST['last_name'];
$location = $_POST['location'];
$email = $_POST['email'];
$pwd = $_POST['pwv'];
$sql = "INSERT INTO info(username, password, first_name, last_name, location, email, pwv)
VALUES('$username','$password','$first_name','$last_name','$location','$email','$pwv');
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = mysql_connect($servername,$username,$password)or die(mysql_error());
mysql_select_db($dbname,$conn);
$sql = mysql_query("INSERT INTO `info` (`username`,`password`,`first_name`,`last_name`,`location`,`email`,`pwv`)
VALUES('".$_POST['username']."','".$_POST['password']."','".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['location']."','".$_POST['email']."','".$_POST['pwv']."')")or die(mysql_error());
?>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I can't understand how to create a prepared statement, and all tutorials I have seen was fetching only column.
My normal sql query
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM files WHERE id=$id ") or die(mysql_error());
$row = mysql_fetch_array($result);
$name = $row['name'];
$date = $row['date'];
Please show me how to create a prepared statement and how to fetch more than one column and insert the date into variables.
First of all it's not a good idea to use SELECT * in production. Instead specify needed columns explicitly. Take a look at https://stackoverflow.com/a/65532/1920232.
Now your code might look like
$id = $_GET['id'];
$db = new mysqli('localhost', 'user', 'password', 'dbname');
$sql = 'SELECT name, date FROM files WHERE id = ?'; //specify columns explicitly
if ($stmt = $db->prepare($sql)) { //create a prepared statement
$stmt->bind_param('i', $id); //bind parameters
$stmt->execute(); //execute query
$stmt->bind_result($name, $date); //bind result variables
$stmt->fetch(); //fetch values
}
$db->close();
echo $id, ' ', $name, ' ', $date;
Note: All error handling intentionally skipped for brevity.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So, I am trying to debug a program of mine, It is a simple PHP code for inserting into a database.
Whenever I run this in my browser :
http://localhost:3456/maps/savemdata.php?descr=Best&lat=-37.12345&lng=122.12345
It should Insert the values into the DB, but what I get is :
Invalid query: 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 'desc, lat, lng ) VALUES ('Best', '-37.12345', '122.12345' )'
at line 1
Savemdata.php
<?php
$hostname = '127.0.0.1:3306';
$dbname = 'login'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
mysql_select_db($dbname) or DIE('Database name is not available!');
// Gets data from URL parameters
$desc = $_GET['descr'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
// Insert new row with user data
$query = sprintf("INSERT INTO markers " .
" (desc, lat, lng ) " .
" VALUES ('%s', '%s', '%s' );",
mysql_real_escape_string($desc),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
DESC is a keyword in mysql. You should take it in backticks ;)
desc is a reserved keyword and happens to be the name of your column. To avoid syntax error, you need to escape it using backtick. eg,
$query = sprintf("INSERT INTO `markers` " .
" (`desc`, `lat`, `lng` ) " .
" VALUES ('%s', '%s', '%s' );",
mysql_real_escape_string($desc),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng));
MySQL Reserved Keywords List
If you have the privilege to alter the table, change the column name to which is not a reserved keyword to avoid problem from occurring again.
Rahul, i would suggest you to use PDO. Try changing your code in the below way.
<?php
$hostname = '127.0.0.1:3306';
$dbname = 'login'; // Your database name.
$username = 'root'; // Your database username.
$password = '';
// database connection
$conn = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
// new data
$desc = $_GET['descr'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
// query
$sql = "INSERT INTO markers (desc,lat,lng) VALUES (:desc,:lat,:lng)";
$q = $conn->prepare($sql);
$q->execute(array(':desc'=>$desc,
':lat'=>$lat,
':lng'=>$lng));
?>