PHP attempt to update a MySQL database doesn't update anything - php

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()

Related

PHP doesn't send data to MySQL

Have some problem I couldn't find solution for, though searched through many sources (and questions here too). So, here it is.
With the PHP-code below I suppose to collect data from a HTML-form and send it to a local WAMP-server. But, though final check shows me "Success!", no new rows in the database's table are found, it stays empty. Names are correct, commands are (as I see it) too, so I just don't know what's wrong.
I hope you guys could help me. ^^
//Check if user submited a form
if (isset($_POST['submit'])) {
//Check if from is properly filled
if (empty($_POST['itemName']) || empty($_POST['itemPic']) || empty($_POST['itemPrice']) || empty($_POST['itemProvider'])) {
echo '<script>alert ("Fill out the form please!")</script>';
} else {
$conn = new mysqli('localhost:3306', 'root', '', 'goods-review');
//Check if connection established
if (mysqli_connect_errno()) {
exit('Connect failed: ' . mysqli_connect_error());
}
//Sending data
$newItem = array('itemName' => $_POST['itemName'], 'itemPic' => $_POST['itemPic'], 'itemPrice' => $_POST['itemPrice'], 'itemProvider' => $_POST['itemProvider']);
$sql = "INSERT INTO goods (itemName, itemPic, itemPrice, itemDate, itemProvider) VALUES ('" . $newItem['itemName'] . "', '" . $newItem['itemPic'] . "', '" . $newItem['itemPrice'] . "', date('Y:m:d, H:i:s'), '" . $newItem['itemProvider'] . "')";
//Check if sent
if ($sql) {
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
$conn->close();
}
}
The code is just assigning a string value to a variable.
$sql = "INSERT ...";
And the string value is not submitted to the database; it's not being executed as a SQL statement. There's nothing magical about the name of the variable. As far as PHP is concerned, the code is just assigning a value to a variable. That's it.
If you want to execute a SQL statement, you need to add code that actually does that. It shouldn't be difficult to find an example of how to do that.
IMPORTANT NOTE: The code in the question appears to create a SQL statement that is vulnerable to SQL Injection. A much better pattern is to use prepared statements with bind placeholders.
Reference: mysqli_prepare
If there's some (unfathomable) reason that you can't use prepared statements, then at a minimum, any potentially unsafe values that are included in the SQL text must be properly escaped.
Reference: mysqli_escape_string
If you have setup the $newItem array first.
Normaly you will validate the user-input and ensure that the user-input has no SQL injections in it.
Read here about it: What is SQL injection?
After that
(You have to add $newItem['itemDate']=date('Y:m:d, H:i:s');)
$sql = "INSERT INTO goods (".implode(', ',array_keys($newItem)).")"
." VALUES ('".implode("', '",$newItem)."')";
if (mysqli_query($conn,$sql)){
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
If you are using this:
you dont have too keep an eye on the right field order
every field value becomes ' around them
you have less code to write
field count and order can change
Finally mysqli_query() returns FALSE if nothing is insert and you can check for that.
Sidenote: Try to use OOP Version of the MYSQLi Extention and Prepared Statments. Read about it here: mysqli, OOP vs Procedural

Echoing Out A Mysql Query

Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}

Having trouble getting two fields to concatenate

hostSo i know how to get the two fields to concatenate from directly inside of MYSQL, but having trouble getting it to work with my PHP.
Directly from MYSQL = SELECT CONCAT(ConfigurationItem, ' - ', ,Buzzword) FROM Buzz;
But how do i incorporate it into this PHP below, I have researched to no end. I want to combine the two fields ConfigurationItem and Buzzword into a field named shortdescription, without having to do it manually through MYSQL everytime the PHP is submitted.
<?php
$con = mysql_connect("host","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buzz_feed", $con);
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword, OccurrenceDate, PostingDate, TierStatus, MasterTicket)
VALUES
('$_POST[BuzzID]','$_POST[ConfigurationItem]','$_POST[Buzzword]','$_POST[OccurrenceDate]','$_POST[PostingDate]','$_POST[TierStatus]','$_POST[MasterTicket]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Buzz Phrase information updated";
mysql_close($con)
?>
I've concatenated them together in php as the insert.
Although there is nothing wrong with catting them in your select statement.
In fact I'd opt for that because it is redundnant-y, you are inserting the same data twice in essence.
But this should do what you are asking for.
I have also corrected your quotation marks in the query.
Also google sql injection
<?php
$con = mysql_connect("host","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buzz_feed", $con);
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword,
OccurrenceDate, PostingDate,
TierStatus, MasterTicket, shortdescription)
VALUES
('".$_POST['BuzzID']."','".$_POST['ConfigurationItem']."',
'".$_POST['Buzzword']."','".$_POST['OccurrenceDate']."','".$_POST['PostingDate']."',
'".$_POST['TierStatus']."','".$_POST['MasterTicket']."',
'".$_POST['ConfigurationItem']."' - '". $_POST['Buzzword']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Buzz Phrase information updated";
mysql_close($con)
?>
I ended up resolving my issue by inserting "ShortDescription" in the INSERT INTO line and then just telling it to insert the two fields I wanted together in the field "ShortDescription" and by using double spaces between my hyphen, I was able to get the desired effect I was looking for which turns out like this "Example - Example" See my code below
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword, OccurrenceDate, PostingDate, TierStatus, MasterTicket, ShortDescription)
VALUES
('$_POST[BuzzID]','$_POST[ConfigurationItem]','$_POST[Buzzword]','$_POST[OccurrenceDate]','$_POST[PostingDate]',
'$_POST[TierStatus]','$_POST[MasterTicket]','$_POST[ConfigurationItem]' ' - ' '$_POST[Buzzword]')";

SQL Update code issue/PHP injection

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)";

I'm going to be auto aupdating info from mysql. How do i get the past info to keep displaying along with the new info submitted into the database?

I've figured out how to display info submitted into mysql, but I haven't figured out how to keep the past info there. It's going to show the current post on top and keep adding on top everytime new info is submitted but only display like 10 posts at a time. I hope I am explaining this well.
How to go about doing this, I am completely lost. I've connected to the database and everything and now im to:
echo $hit, $amount, $category;
and stuck. that is displaying the info submitted, but when i submit new info, that info changes and the past info is gone. My question is, how would i get the past info to stay and get the new info to build on top of past info?
Thanks.
Edit: here's more of the code. also, ive been told about mysqli. i just havent changed it yet.
if(!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('can not use' . DB_NAME . ': ' . mysql_error());
}
$hit = $_POST['hit'];
$amount = $_POST['amount'];
$category = $_POST['category'];
$sql = "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')";
$result = mysql_query($sql);
if(!mysql_query($sql)){
die('Error: ' . mysql_Error());
}
echo $hit, $amount, $category;
mysql_close();
?>
After the insert sql you need to do a select query to retrieve all the rows from the database as you are only echoing the currently set values.
You need to also be mindful of sql injection as the values you're adding to the database are not sanitised in any way. Use a command such as mysql_real_esape_string or htmlentities for this.
Before the line echoing the results...
echo $hit, $amount, $category;
You need to have a select query combined with a while loop and the mysql_fetch_array or mysql_fetch_assoc commands to output the rows from the database. A first check is to see if the records are being added to the table.
At no point in your code are you fetching data from the database. You're simply submitting the data from the form to mysql, and displaying it at the same time.
You can fetch data from mysql by doing something like this:
$data = mysql_query("SELECT hit, amount, category FROM hit");
// Adding MYSQL_ASSOC as a second argument tells mysql_fetch_array that
// we want an associative array (we can refer to fields by their name, not just by number)
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
echo '<p>'
.'Hit: ' . $row['hit']
.', Amount: ' . $row['amount']
.', Category: ' . $row['category']
.'</p>';
}
Keep in mind this is all a simplified version of things, and it needs more work, especially on security. I should probably be using htmlentities() here, depending on the data. And you should definitely be protecting against SQL injection if that data is coming directly from a user.

Categories