Updating MySQL Error but nothing is wrong in code? - php

So I get this error:
Problem updating record. MySQL Error: 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 'WHERE KittenID = '2''
But then in my code:
<?php
if(isset($_POST['Modify']))
{
$connection = mysql_connect("Deleted the login info");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{
$KittenID = $_POST["KittenID"];
$KittenAge = $_POST['KittenAge'];
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Gender = $_POST['Gender'];
$Personality = $_POST['Personality'];
$Activity = $_POST['Activity'];
$Comments = $_POST['Comments'];
$query = "UPDATE Kittenzz
SET KittenID = '$KittenID',
KittenAge = '$KittenAge',
Name = '$Name',
Email = '$Email',
Gender = '$Gender',
Personality = '$Personality',
Activity = '$Activity',
Comments = '$Comments',
WHERE KittenID = '$KittenID'";
$res = mysql_query($query);
if ($res)
{
echo "<p>Record Updated<p>";
}
else
{
echo "Problem updating record. MySQL Error: " . mysql_error();
}
}
}
mysql_close($connection);
}
?>
It makes no sense, I've read those lines of code for an hour, I cannot see the problem. It should run. Can anyone lend me fresh eyes?

Remove the comma near '$comments'
$query = "UPDATE Kittenzz
SET KittenID = '$KittenID',
KittenAge = '$KittenAge',
Name = '$Name',
Email = '$Email',
Gender = '$Gender',
Personality = '$Personality',
Activity = '$Activity',
Comments = '$Comments'
WHERE KittenID = '$KittenID'";

it may possible that in connection username and password in required.
like this :-
$connection = mysql_connect("localhost","username","password");

Related

not response for database

This is the code for database connection in php:
<?php
$connection = mysql_connect("localhost", "root", "root"); // Establishing Connection with Server
$db = mysql_select_db("fimos", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$gender = $_POST["gender"]; //declare gender
$race = $_POST["race"];
$ic = $_POST["icno"];
$name = $_POST["name"];
$old_ic = $_POST["oldic"];
$add1 = $_POST["add1"];
$add2 = $_POST["add2"];
$add3 = $_POST["add3"];
$postcode = $_POST["postco"];
$town = $_POST["tow"];
$state = $_POST["state"];
$home_con = $_POST["homep"];
$fax_contact = $_POST["fax"];
$hp_con1 = $_POST["mobi1"];
$hp_con2 = $_POST["mobi2"];
$email = $_POST["email"];
if($ic !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("INSERT INTO customer_info(cust_gender, cust_race, cust_ic,
cust_name, cust_old_ic, cust_add1, cust_add2, cust_add3, cust_postcode,
cust_town, cust_state, cust_home_con, cust_fax_contact, cust_hp_contact1,
cust_hp_contact2, cust_email)
VALUES ('$gender', '$race', '$ic' , '$name', '$old_ic', '$add1', '$add2',
'$add3', '$postcode', '$town', '$state', '$home_con', '$fax_contact',
'$hp_con1', '$hp_con2', '$email')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
Hi guys, I want to ask about the database connection, is it my code wrong somewhere?
Because I cant found any error in the code.
I click button register should come over this page to store the data.
when I come to this page display all blank.
I try to change the database name also no response.
I hope you guys can help me.
Thanks.
It should be:
$connection = mysql_connect("localhost", "root", ""); //empty the third parameter. If you have password then insert that in your third parameter
Paste this code inside your if condition so that it will return error from your sql query.
if (!$query) {
die('Invalid query: ' . mysql_error());
}
Try to use the PDO extension instead of mysql & mysqli function. The mysql_* functions are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi there are lots of benefits of using PDO over mysqli.
Add the above code
if($ic !=''||$email !=''){
$query = mysql_query("your query");
if (!$query) {
die('Invalid query: ' . mysql_error());
} else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
}

PHP, mySQL. saving on more than one different table using php action script

I am working on one php script and would like to insert data to three different tables. How can I do that on php action script.
error_reporting(0);
$datee=$_POST['date'];
$company=$_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter=$_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company=$_POST['company'];
$agents=$_POST['agents'];
$resumes = $_POST['resumes'];
$structure=$_POST['structure'];
$sql = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
"INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
The problem is, it is only saving date on one table.
please assist me as I am new to php.
Thanks in advance.
$link = mysqli_connect("host", "username", "password", "database");
$sql = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone') ;";
$sql . = "INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
mysqli_multi_query($link, $sql);
Sorry for late reply.
If you are using mysql: (Not recommended due to unsecure)
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('YourDBName') or die("cannot use database");
if(isset($_POST['Submit'])){
$datee = $_POST['date'];
$company = $_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter = $_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company = $_POST['company'];
$agents = $_POST['agents'];
$resumes = $_POST['resumes'];
$structure = $_POST['structure'];
}
$result = mysql_query("
INSERT INTO job_spec_contact (contact_info_key, datee, company_name, Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone');
INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure');
");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['datee'];
echo $row['company_name'];
......
}
mysql_free_result($result);
?>
If you are using mysqli: (Recommended),
$conn = mysqli_connect('localhost','username','password') or die("cannot connect");
mysqli_select_db($conn, 'YourDBName') or die("cannot use database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['Submit'])){
$datee = $_POST['date'];
$company = $_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter = $_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company = $_POST['company'];
$agents = $_POST['agents'];
$resumes = $_POST['resumes'];
$structure = $_POST['structure'];
}
$query = "INSERT INTO job_spec_contact (contact_info_key, datee, company_name, Physical_Address, recruitment_person, email, Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
$query .= "INSERT INTO job_company_infor (info_key, company_specialization, no_of_agents, no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
if ($mysqli->multi_query($query)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);//test here your values.
//$datee = $row['datee'];
}
$result->free();
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
Hope this helps.
Note:
Check always POST is present or not by isset. (assume, input name Submit)
Use MySQLi/PDO instead of MySQL to avoid SQL injection.
Debug code by using echo, print_r, var_dump, etc.,
Try to use field names are in same pattern. For ex, Instead of Physical_Address, use physical_address like other fields. Telephone to telephone. datee to job_contact_date, etc.,
Just execute your queries one by one. And DO NOT write error_reporting(0); or the errors won't show. Plus where is your DB ?
$sql1 = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
$sql2 = "INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
mysqli_query($db,$sql1) or die('error '.$sql1.'<br>'.mysqli_error($db));
mysqli_query($db,$sql2) or die('error '.$sql2.'<br>'.mysqli_error($db));

Mysqli_query returns false and Mysqli_error returns NULL? [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 1 year ago.
I've been creating a booking system, and creating appointments, but my SQL statement is not working. I've been trying to find a solution but to no avail.
Listed below is my php code. My first SQL statement works perfectly and returns the correct ClientID, however, the second SQL statement does not insert it all into the database. I have done var_dumps on result, returning bool(false), as well as mysqli_error on the result, returning null.
My error message at the end only displays the echo'd message, and not the mysqli_error or error number also.
(Note: some values are changed/removed to protect data)
<?php
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "appointmentinformation";
$tablenamed = "clientinformation";
$connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");
$clientusername = $_SESSION['Username'];
$sql = "SELECT ClientID FROM $tablenamed WHERE Username = '$clientusername' LIMIT 1";
$results = mysqli_query($connection, $sql);
if (! $results) {
echo ("Could not select the data : " . mysql_error());
} else {
$datarows = mysqli_fetch_row($results);
$clientid = $datarows[0];
}
$date = $_POST["Date"];
$month = $_POST["Month"];
$year = $_POST["Year"];
$time = $_POST["Time"];
$length = $_POST["Length"];
$date = stripslashes($date);
$month = stripslashes($month);
$year = stripslashes($year);
$time = stripslashes($time);
$length = stripslashes($length);
$date = mysqli_real_escape_string($date);
$month = mysqli_real_escape_string($month);
$year = mysqli_real_escape_string($year);
$time = mysqli_real_escape_string($time);
$length = mysqli_real_escape_string($length);
$query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Month, Year, Time, Price) VALUES ('$clientid', '$length', '$date', '$month', '$year', '$time', '$price')";
$result = mysqli_query($connection, $query);
if ($result) {
header("Location:UserCP.php");
} else {
echo ("Could not insert data : " . mysqli_error($result) . " " . mysqli_errno());
}
?>
$query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Month, Year, Time, Price) VALUES ('$clientid', '$length', '$date', '$month', '$year', '$time', '$price')";
$result = mysqli_query($connection, $query);
if ($result) {
header("Location:UserCP.php");
} else {
echo ("Could not insert data : " . mysqli_error($result) . " " . mysqli_errno());
}
The result returned from mysqli_query is null. This sends you down the else branch of the code. Then you coded mysqli_error($result) which equals mysqli_error(null).
The documentation I have read says to initialize a variable with a "link" to the query. You did this with:
$connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");
You now want to code it as mysqli_error($connection) and mysqli_errno($connection).
An additional suggestion. Add this code right after your mysqli_connect statement.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

PHP Insert values into Database at certain position

So I'm currently creating a Online Game and already got the login and registering working but now I'm working on submitting Stats such as health and a player's level and retrieving that.
So in this PHP file I'm able to retrieve the info of a certain player but I don't know how to submit new stats into a certain player's row. I'm still learning PHP so please help me out.
<?php
// Database Things =========================================================
$host = "localhost";
$user = "lyth_com_Spillnk";
$password = "INTERESTED?";
$dbname = "lythumn_com_Spillnk";
mysql_connect($host, $user, $password) or die("Can't connect into database");
mysql_select_db($dbname)or die("Can't connect into database");
// =============================================================================
$Act = $_GET["Act"];// what is action, Submit or Retrieve?
$nick = $_GET["User"];
$health = $_GET["Health"];
$level = $_GET["Level"];
$xcood = $_GET["X"];
$ycood = $_GET["Y"];
if($Act == "Retrieve"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$total = mysql_num_rows($result_id);
if($total) {
$datas = #mysql_fetch_array($result_id);
echo ($datas["Health"], $datas["Level"], $datas["X"], $datas["Y"]);
}
}
if($Act == "Submit"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$query = "INSERT INTO Stats (Username, Health, Level, X, Y) VALUES('$nick', '$health', '$level', $'xcood', $'ycood')";
mysql_query($query) or die("ERROR");
mysql_close();
echo "Submitted";
}
// Close mySQL Connection
mysql_close();
?>
It's mostly concercing this piece of code:
if($Act == "Submit"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$query = "INSERT INTO Stats (Username, Health, Level, X, Y) VALUES('$nick', '$health', '$level', $'xcood', $'ycood')";
mysql_query($query) or die("ERROR");
mysql_close();
echo "Submitted";
}
As you are able to see I already retrieve the Index of where the player's stats are located so how do I insert values there?
Thanks in advance!

Insert form data in one table and then update an enum value in a different table?

I am using a code to insert a users form data into the database, that bit works fine. However, i also want to run another query and update an enum value 'form2_completed?' from No to Yes. I have added in the update query and now for some reason the script is not working and says 'ERROR'
Can someone please show me where i am going wrong. thanks
<?php
session_start();
$db_hostname = 'localhost';
$db_database = 'hewden1';
$db_username = 'root';
$db_password = '';
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$cname = $_POST['cname'];
$creg = $_POST['creg'];
$address = $_POST['address'];
$post = $_POST['post'];
$contactn = $_POST['contactn'];
$contactt = $_POST['contactt'];
$email = $_POST['email'];
$vat = $_POST['vat'];
$ipaddress = $_SERVER["REMOTE_ADDR"];
$sql="INSERT INTO supplier_registration (company_name, company_reg_number, company_address, company_postcode, contact_name, contact_number, contact_email, company_vat_number, date_time, user_ip)
VALUES ('$cname', '$creg', '$address', '$post', '$contactn', '$contactt', '$email', '$vat', NOW(), '$ipaddress')";
$sql="UPDATE supplier_session SET form2_completed? = 'Yes' WHERE form2_completed? = 'No'";
$result = mysql_query($sql);
if($result){
$success = "<div class='success'></div>"; // use the $success
//encode the URL parameter as :
$success = urlencode($success);
header("Location: index.php?success=$success");
}else {
echo "ERROR";
}
?>
You are overwriting the variable $sql and not running INSERT. Try:
$sql="INSERT INTO supplier_registration (company_name, company_reg_number, company_address, company_postcode, contact_name, contact_number, contact_email, company_vat_number, date_time, user_ip)
VALUES ('$cname', '$creg', '$address', '$post', '$contactn', '$contactt', '$email', '$vat', NOW(), '$ipaddress')";
$result = mysql_query($sql);
$sql="UPDATE supplier_session SET form2_completed? = 'Yes' WHERE form2_completed? = 'No'";
$result = mysql_query($sql);
Please note that the method you have used is deprecated from php 5.5.0. so i suggest you consider mysqli or PDO. examples can be found in below php manual links
http://www.php.net/manual/en/mysqli.query.php
http://www.php.net/manual/en/pdo.query.php

Categories