I have this code which doesn't work for some reason
$con = mysql_connect("$server", "$user", "$pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('$db', $con);
// BLOCK 1
$supplier=$_POST["supplier"];
$supplierNowBalance =$_POST["supplierNowBalance"];
$supplierBalance=$supplierNowBalance - $supplier;
mysql_query("UPDATE inv SET balance='".$supplierBalance."' WHERE username='supplier' AND name='bingo'");
echo $supplierBalance;
// END OF BLOCK 1
Everything before and after the UPDATE statement works. I copied the update statement to PHPMyAdmin and it updates just fine! I don't get it. for some reason php is not running the mysql_query
Few tips: I have few of this block of code in the program so it goes through all of them posts and calculates, and updates
I have tried every possible combination for the mysql query (with and without 's )
###############ANSWER__________
Thanks for the answer but I figured it out. Apparently PHP is desperate to have double quote "" around the connection string.
On line 6, when I descrbed the database variable
mysql_select_db('$db', $con);
I had single qoute, I changed it to double qoute and bam, it worked, Thanks
mysql_select_db("$db", $con);
balance is numeric right? you shouldn't wrap it with single quotes.
mysql_query("UPDATE inv SET balance= " . $supplierBalance . " WHERE username='supplier' AND name='bingo'");
using PDO makes it invulnerable with SQL INJECTION
<?php
// other codes
$stmt = $dbh->prepare("UPDATE inv SET balance = ? WHERE username = ? AND name = ?");
$stmt->bindParam(1, $supplierBalance);
$stmt->bindParam(2, 'supplier');
$stmt->bindParam(3, 'bingo');
$stmt->execute();
// other codes
?>
Thanks for the answer but I figured it out. Apparently PHP is desperate to have double quote "" around the connection string.
On line 6, when I descrbed the database variable
mysql_select_db('$db', $con);
I had single qoute, I changed it to double qoute and bam, it worked, Thanks
mysql_select_db("$db", $con);
Related
I installed MySql on my Raspberry Pi 2 Model B+ a few days ago to see if I could use it, PHP, phpmyadmin, and Apache to make an accessible database to organize and catalog books that are around the house. I have a table in a MySQL database set up as a prototype with three columns; Booknumber (set to auto-increment), title, and authorLastName. I'm trying to use a form to insert books into table beta, in database bookProof.
Here's the code for the form:
<html>
<body>
<form action="catalog.php" method="POST">
<p>Book Title: <input type="text" name="title"></p>
<p>Author's Last Name: <input type="text name="authorlastname"></p>
</form>
</body>
</html>
Which links to "catalog.php", which is:
<?php
define('DB_NAME', 'bookProof');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Could not connect: " . $conn->connect_error);
}
$value = $_POST["title"]
$value2 = $_POST["authorlastname"]
$sql = "INSERT INTO beta ('title', 'authorLastName') VALUES ('".$value."', '".$value2."')"
$query = mysqli_query($conn,$sql);
if ($conn->($sql) === TRUE) {
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When demoform.php is opened, it functions normally, but when the "Add Books" button is clicked, it goes to catalog.php as intended, but the catalog.php page is blank, the table is unchanged, and Google Chrome's "Inspect" tool gives the error:
POST http://192.168.254.11/Library/catalog.php 500 (Internal Server Error) catalog.php:1
If anyone knows how to get the input to the database, please let me know.
Note: This is just a home system, so security is not a priority (I don't need SQL code injection protection).
Your note, "...security is not a priority (I don't need SQL code injection protection)" - you might think that, but you should do it anyways. Not only does it protect your database should your system be exposed (or made public at a later time), it will handle strings automatically for you, so that your query won't break if your strings have quotes ' in them.
One issue is that you're using singlequotes around column and table names. This should be backticks, or none at all. Then you were missing a semicolon ; after defining your $value, $value2 and $sql strings.
Then you're doing something a bit odd - which is also causing a parse-error (Had you enabled error-reporting and checked your logs, you'd see a "Parse error: syntax error, unexpected (" error in your logs), you're querying the table with mysqli_query(), but then you try to do it again - except you're trying to query on the querystring, and not the query method. Note the comments I've added in the code below.
// Don't use singlequotes ' for columns and table-names
// Use backticks ` - quotes are for strings
$sql = "INSERT INTO beta (`title`, `authorLastName`) VALUES ('".$value."', '".$value2."')"; // You were also missing a semicolon here!
// $query = mysqli_query($conn,$sql); // Remove this line, as you're attempting to query it twice
if ($conn->query($sql) === TRUE) { // You're missing the query() method here
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using prepared statements won't be that much of a difference, and you really should do it. There's absolutely no reason to not use prepared statements! Look how little changes that have to be made!
$sql = "INSERT INTO beta (title, authorLastName) VALUES (?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ss", $value, $value2);
$stmt->execute();
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You've also got some invalid HTML which would cause issues - the following line had a missing quote to close off the type attribute.
<input type="text" name="authorlastname">
I suggest you read the following documentation and articles
When to use single quotes, double quotes, and backticks in MySQL
How can I prevent SQL injection in PHP?
PHP manual on mysqli_stmt::bind_param
How to get useful error messages in PHP?
PHP Parse/Syntax Errors; and How to solve them?
As a final note, you should check that the form was submitted and that it has values before inserting into the database. Also, using variable-names like $value and $value2 are not really descriptive - you should avoid it and use proper names for your variables.
Hello I'm new in Android and I wanna send a text from Android with space (" My Name is Oliver Queen ") to MySQL database.
I use this script in PHP:
<?php
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
$id=$_GET['id'];
$project=$_GET["a"];
// Create connection..
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "$project";
$sql= $sql= "UPDATE user SET project = \"$project\" WHERE id= '$id'";
$result = $conn->query($sql);
$conn->close();
?>
In MySQL I found only ("My") The first word before space!
Plzz someone Help Mee !!!!!!
Check the value of $project variable;
My bet is that you send values over a GET request, and not properly encoding them.
If your $project value is indeed "My" like I guess, then look up on you Android part, and look up on how to do url encoding (should be very simple in Java) - look for the equivalent of http://php.net/manual/en/function.urlencode.php - this should resolve your problem.
Also after you get it working, modify the code to deal with SQL Injections, switch to using PDO for DB access, and prepared statements, this would increase the security of your code.
first of all, you should fix your query by using single quotes around the varchar attribute not the numeric, also pay attention to $sql = $sql = you declared it twice:
$sql= "UPDATE user SET project = '$project' WHERE id= $id";
then, you are trying to receive a string by GET method $project=$_GET["a"];, so your URL should be well encoded.
I am having an issue with my SQL Update script.
It prints "Motto Changed" but doesn't update the row. My code is all correct according to many tutorials. Please Help
$sql="UPDATE loadout SET motto='".$_POST['motto']."' WHERE steamid='".$steamid."'";
UPDATE AGAIN:
<?php
require "../requires/php/steam.php";
$dbhost = '**';
$dbname = 'battlefield';
$dbuser = 'battlefield';
$dbpass = '**';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$authserver = bcsub( SteamID(), '76561197960265728' ) & 1;
$authid = ( bcsub( SteamID(), '76561197960265728' ) - $authserver ) / 2;
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
mysql_select_db($dbname, $con);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "Motto Changed";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo"Motto changed on {$n} row(s)";
mysql_close($con)
?>
Never interpolate $_POST variables directly into SQL strings. You can't trust $_POST variables, they may easily contain characters that modify your SQL syntax, and that's what causes SQL injection vulnerabilties.
The weird thing is that you create an escaped version as $motto and then you never use it (as per comment from #Arth).
Always escape strings that you interpolate into SQL, even if you think they are "safe." For example, your $steamid contains only literal text that you control, plus a couple of integers. That should be safe, but what if some other developer changes the format of a steamid next year? If you escape it, you can't go wrong.
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
Of course, the best practice is to use query parameters. You are using PHP's deprecated mysql extension, which doesn't support query parameters. But I understand if you're not ready to rewrite a lot of code to switch to PDO. When you are, follow examples in How can I prevent SQL-injection in PHP?
Another issue: if you want to know if the UPDATE affected rows, don't assume it did just because the UPDATE didn't return an error. It's not an error if your condition in your WHERE clause simply matched zero rows. It's also not an error if the UPDATE matched a row, but the motto already contained the string you tried to set.
After the UPDATE, check the number of affected rows:
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo "Motto changed on {$n} row(s)";
My code doesn't insert any records to mysql. What is wrong? I am really confused.
I have designed a form and I want to read data from text box and send to the database.
<?php
if(isset($_post["tfname"]))
{
$id=$_post["tfid"];
$name=$_post["tfname"];
$family=$_post["tffamily"];
$mark=$_post["tfmark"];
$tel=$_post["tftell"];
$link=mysql_connect("localhost","root","");
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("university",$link);
$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'$name','$family',$mark,$tel)";
mysql_query($insert,$link);
}
mysql_close($link);
?>
You'd better to put quotation mark for id, mark and tel after values in your query. Also as #Another Code said, you must use $_POST instead of $_post in your code. Try this and tell me the result:
<?php
if(isset($_POST["tfname"])) {
$id=$_POST["tfid"];
$name=$_POST["tfname"];
$family=$_POST["tffamily"];
$mark=$_POST["tfmark"];
$tel=$_POST["tftell"];
$link=mysql_connect("localhost","root","");
if (!$link) {
die('Could not connect: ' . mysql_error());
} else {
mysql_select_db("university",$link);
$insert="insert into student
(sid,sname,sfamily,smark,stel) values
('$id','$name','$family','$mark','$tel')";
mysql_query($insert,$link) or die (mysql_error());
mysql_close($link);
}
} else {
die('tfname did not send');
}
?>
Use mysql_query($insert,$link) or die (mysql_error()); to fetch the error message.
With the code you've provided it could almost be anything - to do some tests... have you echo'd something to confirm you are even getting the tfname in POST? Does it select the database fine? Do the fields $id, $mark, and $tel need single quotes around them as well? We need to know more about where the code is not working to provide more help but that snippet appears as though it should be running, in the interim, please use some echo's to narrow down your problem!
Try to run the generated sql query in the sql query browser. Get the query by "echo $insert" statement.
change the $insert to:
$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'".$name."','".$family."','".$mark."','".$tel."')";
further set ini_set('display_errors',1) so that php displays the error messages as required.
Lastly, whenever doing a mysql query, try to use or die(mysql_error()) in the query so that if somethings wrong with mysql or syntax, we are aware.
$q = mysql_query($query) or die(mysql_error());
I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()