Update query in MySQL and PHP not working - php

PHP usually works pretty much straight out of the box, but I cannot get this query to work. I am attempting to update a simple record. My code is as follows.
<?php
$customername=mysql_real_escape_string($_POST['customername']);
$contact=mysql_real_escape_string($_POST['contact']);
$customerorder=mysql_real_escape_string($_POST['customerorder']);
$orderplaced=mysql_real_escape_string($_POST['orderplaced']);
$staffmember=mysql_real_escape_string($_POST['staffmember']);
$daterequired=mysql_real_escape_string($_POST['daterequired']);
$status=mysql_real_escape_string($_POST['status']);
$paid=mysql_real_escape_string($_POST['paid']);
$delivery=mysql_real_escape_string($_POST['delivery']);
$ordercontent=mysql_real_escape_string($_POST['ordercontent']);
$orderid=mysql_real_escape_string($_GET['orderid']);
mysql_connect("localhost", "xxxx", "xxxxxxx") or die("Connection Failed");
mysql_select_db("xxxxxx")or die("Connection Failed");
$query = "UPDATE ordermanager_orders SET customername='$customername', contact='$contact', ordernumber='$customerorder', placedby='$orderplaced', requiredby='$daterequired', status=$status', staffmember='$staffmember', paid='paid', delivery='$delivery', ordercontent='$ordercontent' WHERE order='$orderid'";
if(mysql_query($query)){
echo "updated";}
else{
echo "fail";}
?>
The values are being posted or "Getted" from another page. They are definitely coming through as otherwise it comes up with errors. At the moment it simply comes up with 'failed' as per the code.
I have tried numerous variants of code found on the internet, to check if my coding was correct, however I still cannot get it to work.

I wonder if u have tried to print_r your $query to check.
1st. Shift your connection string to the top most.
2nd. status=$status' <<=== less 1 quote

I thought you had to connect to the database before you were able to use mysql_real_escape_string()? Try connecting above all other code.
The status section of the query is also missing a quote mark.

Try changing by adding a comma
status=$status' to status='$status'
And FYI change paid='paid' to paid='$paid' to ensure the correct value is passed

Your error is because of not handling your status update correctly: status=$status' must be status='$status'.
You would have figured this if you'd put a mysql_error() in your 'fail' section.

Related

php mysql Insert into not working

So what I am trying to do is a very basic and straight way of inserting a record into mysql db.
It is just something I have done few times before, however for some reason it is not working with me this time.
So in the following couple of lines of code I will show my code, which basically do the following
1- Check if the user exists in the DB (An existing user is a user with the same email)
2- If the user exists in the DB then it sends an http response with a status code of 409 which means duplication.
(Anyway note that this works perfectly, which implies the connection was made successfully to the DB, and it was able to retrieve any exact user, if any)
3- If the user does not exist it should be inserted in the DB (Here is the problem)
My Code
//Checking if the user exist
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
// Close Connection
mysql_close($con);
echo "409";
}
else{
mysql_query("INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')",$con);
// Select the record
$user_id = mysql_insert_id();
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
// Close Connection
mysql_close($con);
echo "200 " . $result['username'];
}
I googled the possible solutions for this issue, however all similar issues I went through were because of syntax errors.
Any suggestions? Thanks in advance :)
What is the exact error message you are getting? Copy/paste that here, please.
Also, the only odd thing I see is that you are doing the SELECT commands with a variable $table_name, and in the INSERT command you are hard-coding a table name..? Maybe that's it?
INSERT INTO samam_users ...
just put the same table name variable there?
INSERT INTO $table_name ...
Let me know if this helps. :)
$sql = "INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')";
if(!mysql_query($sql,$con)) {
die(mysql_error());
}else {
echo 'inserted succesfully';
}
mysql_error() will give you information about why your query isn't working - allowing you to debug it.
Also don't use mysql_*, it's going to be deprecated and there are much better more secure options like MySQLi or preferably PDO
I think you have to put all the values in INSERT command in double quotes instead of single quote

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

Could anyone with MySQLi experience help me with this short SELECT code?

I have researched my question but there just isn't much help out there for MySQLI functions. I'm also new here so, please bear with me.
I have a test database named "website" and it contains a table called "users" which has data for all of the members of my website. In a separate file I have the php code that connects to my localhost and selects the database "website." I'm using the newest functions of MySQL so instead of the connection string containing mysql_connect it contains mysqli_connect. The registration process works great and I can find no error in any of the other code that uses the mysqli functions.
My include file (connect.php)
<?php
$link = mysqli_connect("localhost", "useracc", "useracc1", "website");
?>
I set up a test script for the login section.
<?php
include('connect.php');
$user = $_POST['user'];
$query = "SELECT birthday FROM users";
$result = mysqli_query($link, $query) or die ("RESULT ERROR");
echo "$user";
echo "$result";
?>
There is a password box on the previous page but for the test script I left that out and so far, only the $user is shown on the page. I get no error even when I replace "RESULT ERROR" with mysqli_error($link). I've tried interchanging ' for " in every part of the code that uses quotes but that didn't work. I've tried rewording the $query line but that also had no effect. I'm really new to MySQL and php so if you guys could tell me where I'm going wrong I'd really appreciate it.
Thanks for reading my question. Have a great day.
Add the following lines to the connect.php after you connect line
if (mysqli_connect_errno()) {
printf("Can't connect Errorcode: %s\n", mysqli_connect_error());
exit;
}
this will ensure the connection is made without any errors and return them if there are ...

Add MySQL entry from PHP web page

I am developing a web application that allows a user to add entries to a MySQL database through a web form. The web form posts to the same page, some PHP code captures that data and sends it to MySQL. For whatever reason, nothing ever makes it to MySQL. This is the code I have so far that isn't working:
<?php
include("config.inc.php");
$Name=$_POST['AddName'];
$Group=$_POST['AddGroup'];
$Grade=$_POST['AddGrade'];
$Position=$_POST['AddPosition'];
$Email=$_POST['AddEmail'];
$HomeAddress=$_POST['AddHomeAddress'];
$City=$_POST['AddCity'];
$State="SC";
$Zip=$_POST['AddZIP'];
$CellPhone=$_POST['AddCellNumber'];
$HomePhone=$_POST['AddHomeNumber'];
$FirstPeriod=$_POST['AddFirstPeriod'];
$SecondPeriod=$_POST['AddSecondPeriod'];
$ThirdPeriod=$_POST['AddThirdPeriod'];
$FourthPeriod=$_POST['AddFourthPeriod'];
$FifthPeriod=$_POST['AddFifthPeriod'];
$SixthPeriod=$_POST['AddSixthPeriod'];
$SeventhPeriod=$_POST['AddSeventhPeriod'];
$Homeroom=$_POST['AddHomeroom'];
$dbpassword=$_POST['AddPassword'];
$con = mysql_connect("127.0.0.1","$username","******");
if (!$con)
{
die();
}
mysql_select_db("$database", $con);
$sql="INSERT INTO names (Name,Grp,Grade,Position,Email,HomeAddress,City,State,Zip,CellPhone,HomePhone,FirstPeriod,SecondPeriod,ThirdPeriod,FourthPeriod,FifthPeriod,SixthPeriod,SeventhPeriod,Homeroom)
VALUES('$Name','$Group','$Grade','$Position','$Email','$HomeAddress,'$City','$State','$Zip','$CellPhone','$HomePhone','$FirstPeriod','$SecondPeriod','$ThirdPeriod','$FourthPeriod','$FifthPeriod','$SixthPeriod','$SeventhPeriod','$Homeroom')";
if (!mysql_query($sql,$con))
{
die();
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Try this and see what it says:
if (!mysql_query($sql,$con))
{
die(mysql_error());
}
Try inserting echo mysql_error();. This should give you at least a starting place to where your query is incorrect.
mysql_close($con) should have a semi-colon at the end.
check your log for errors.
use mysql_real_escape_string
PHP hides errors. To debug, start by placing these two lines as the first lines within the <?php tag
error_reporting(E_ALL);
ini_set('display_errors', '1');
Also in case the error was in mysql you can do:
print_r(mysql_fetch_array(mysql_query("SHOW WARNINGS", $con)));
or
print_r(mysql_fetch_array(mysql_query("SHOW ERRORS", $con)));
Directly after the mysql query you think may have failed.
die(mysql_error());
will fix it.
Also have a look at escaping. It would be very easy to inject into the current code.
If you are not going to escape (I don't know when you would do that) you might as well use the $_POST rather than assigning to a variable and using the variable.
change your database selection to
mysql_select_db("database name")
or
mysql_select_db($database);
your are trying to select a database named "$database" with a dollar sign as a string, not the name in that variable.
also, use
mysql_real_escape_string($sql) to escape those variables.(avoiding sql injecion) you can find links about it in other comments.
change
$sql="INSERT INTO names (Name,Grp,Grade,Position,Email,HomeAddress,City,State,Zip,CellPhone,HomePhone,FirstPeriod,SecondPeriod,ThirdPeriod,FourthPeriod,FifthPeriod,SixthPeriod,SeventhPeriod,Homeroom)
VALUES('$Name','$Group','$Grade','$Position','$Email','$HomeAddress,'$City','$State','$Zip','$CellPhone','$HomePhone','$FirstPeriod','$SecondPeriod','$ThirdPeriod','$FourthPeriod','$FifthPeriod','$SixthPeriod','$SeventhPeriod','$Homeroom')";
to
$sql="INSERT INTO names (Name,Grp,Grade,Position,Email,HomeAddress,City,State,Zip,CellPhone,HomePhone,FirstPeriod,SecondPeriod,ThirdPeriod,FourthPeriod,FifthPeriod,SixthPeriod,SeventhPeriod,Homeroom)
VALUES('$Name','$Group','$Grade','$Position','$Email','$HomeAddress','$City','$State','$Zip','$CellPhone','$HomePhone','$FirstPeriod','$SecondPeriod','$ThirdPeriod','$FourthPeriod','$FifthPeriod','$SixthPeriod','$SeventhPeriod','$Homeroom')";

How do I select mysql database in php?

I have this code:
if(!mysql_connect($host,$user,$passwd)){
die("Hoops, error! ".mysql_error());
}
...no error from here.
if(!mysql_select_db($db,$connect)){
$create_db = "CREATE DATABASE {$db}";
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
}
..."no database selected" error from here.
I would like to select database if it exists and if doesn't then create it and select it.
Why is my code not right?
Thank you in advance
Where are you saving the value returned by mysql_connect()? Don't see it here. I assume $host, $user, $password and $db are properly set ahead of time. But you're passing a param to mysql_select_db that may not be properly set.
$connect = mysql_connect($host,$user,$passwd);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($db,$connect)) ...
Start by checking to see if you can select without the CREATE query first. Try a simple SELECT query to start. If you can connect, select the db, and execute a SELECT query, that's one step. Then try the CREATE query. If that doesn't work, it's almost certainly a matter of permissions.
You might need database create permissions for the user attempting to create the database.
Then you need to operate on a valid connection resource. $connect never looks to be assigned to the connection resource.
Why not simply use the CREATE DATABASE IF NOT EXISTS syntax instead?
Something like this ...
$con = mysql_connect('localhost');
$sql = 'CREATE DATABASE IF NOT EXISTS {$db}';
if (mysql_query($sql, $con)) {
print("success.\n");
} else {
print("Database {$db} creation failed.\n");
}
if(!mysql_select_db($db,$connect)){
print("Database selection failed.\n");
}
You should check the return value of mysql_query() - currently if any of those calls fail you won't know about it:
if(!mysql_select_db($db,$connect)){
if (!mysql_query("CREATE DATABASE $db", $connect)) {
die(mysql_error());
}
if (!mysql_select_db($db, $connect)) {
die(mysql_error());
}
}
Change the line
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
To
mysql_query($create_db,$connect);
mysql_select_db($db);*
and it should work.
you could try w3schools website. They have a very simple and easy to learn tutorial for selecting database. The link is : http://www.w3schools.com/php/php_mysql_select.asp
Hope this help :)
I would like to thank to all of you, however I found fault on my side. This script was in class and one of variables were not defined inside this class. So I'm really sorry.
I don't know how to consider the right answer, but I noticed my mistake after reading Clayton's answer about not properly set parameters, so I guess he is the winner ;)

Categories