PHP MySQL INSERT not inserting nor any error is displayed - php

I have got this code so insert values into a table in MySQL through PHP. I have tried all the possible Insert syntax, it does not insert the data... this are the codes that i used.
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('".$param."','".$param1."')";
$result = $mysql->query($sql);
if($result)
echo "successful";
else
echo mysql->error;
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;
I even tried the following sql syntax
"INSERT INTO trail (User_Name, Quiz_ID) VALUES ('$param1','$param1')";
"INSERT INTO `trail` (`User_Name`, `Quiz_ID`) VALUES ('$param1','$param1')";
and i tried several other none of them inserts anything into the table. and this is the table in MySQL;
trail
User_Name varchar(35)
Quiz_ID varchar(35)
It does not insert anything nor does it display any error. And I have the correct DB connection because i am able to Select from the table. Its just the insert that is tricky.
Any help would be much appreciated.
Thanks

Just a note if someone is running on similar problems:
I had a similar issue --- Insert query working on PHPMyAdmin but not working on PHP and not issuing any errors (result was true all the time).
The reason is that I was starting a transaction but forgetting to commit it...
$mysqli->autocommit(FALSE);
$mysqli->query( "START TRANSACTION" );
Never forget this:
$mysqli->commit();
It is a silly error, I know, but I was so focused on the query mistery that I forgot the transaction statements a few lines above.

Check the mysqli::$errno first.
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;

What I have done is if you don't have a debugger installed, just have it email you the query. This way you can see what the final query is and if you have access to something like phpMyAdmin try manually running the query and see what happens. Another thing, make sure that you are searching for your inserted record correctly, if you are using a search query because of the number of records make sure the WHERE condition is right, that has burned me a few times.
EDIT
Missing symbol around names maybe. I have to run all my MySQL queries like
`nameOfThing`
instead of just nameOfThing
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO `trail` (`User_Name`, `Quiz_ID`) VALUES ('".$param."','".$param1."')";
$result = $mysql->query($sql);
if($result)
echo "successful";
else
echo mysql->error;
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;

FYI, you are inserting $param1 twice.
You also don't have a ';' after echo "successful".
I'd suggest you clean up the code example, and try things again, and let us know.
Things to clean up
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('$param','$param1')";
You don't need to concatenate the variables in a string concatenate, you can interpolate. However, you actually should use PDO with a prepared statement to avoid the potential for SQL injection.
Add that missing ;
put that first check of if(mysql->errno==0) in (unless you are going to switch to PDO for this stuff).
Fix mysql->error to be mysql->error()
Maybe some other things from the comments.

Well, if the following code produce no error and shows 1 affected row, most likely you are looking for the result in the wrong database.
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('testing','1')";
$mysql->query($sql);
var_dump($mysql->error,$mysql->affected_rows);

My tables were InnoDB tables and when i changed my tables to MyISAM the insert worked fine. Well i have never encountered this problem before. Well that did the trick for the time being.
If i want to use InnoDB engine for transactions? How can i get php to be able to insert values in InnoDB table? Any one got any suggestion? And i am using WAMP server and the MySQL is version 5.5.24. And i did change the InnoDB conf in my.ini but that did not seem to work either?

try this
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('".$param."','".$param1."')"; $result = $mysql_query($sql); if($result){ echo "successful";} else { echo " not successful;}

Related

PHP PDO query not inserting - Error HY093

After a lot of searching the web, the times I see this error, it looks really scenario specific. So far, I haven't found one that matched my scenario. I think my issue is coming from a prepared statement with spatial data type params.
The way I'm executing my code is:
$sql = $conn->prepare("INSERT INTO states(`name`, `poly`) VALUES(':name',GeomFromText('GEOMETRYCOLLECTION(:coords)'));");
$res = $sql->execute(['name'=>$name, 'coords'=>$coords]);
if($res){
echo "... Successfully Inserted<br><br>";
}
else{
echo "... Failed<br><br>";
print_r($sql->errorInfo());
echo "<br><br>";
}
The above is failing. The connection to the database has been tested. Since these are rather large geometry sets, instead of pasting my code, I'll show how I verified my SQL:
Dumping a raw SQL file and copy/pasting the SQL into a phpMyAdmin window, everything inserted just fine.
$sqlStr = "INSERT INTO states(`name`, `poly`) VALUES('$name',GeomFromText('GEOMETRYCOLLECTION($coords)'));";
$check = file_put_contents('./states/'.$name.'2.sql', $sqlStr);
So it's because of this, that I believe my sql is correct, but it my problem is likely due to the prepare/execute portion somehow. I'm not sure if spatial data types can't be assigned like this?
Edit
I also want to note that I am on PHP version 5.5.9 and I've executed queries in the original method, with the params in the execute just fine.
There's no way the code at the end could be working. Parameters in the query must not be put inside quotes.
Since GEOMETRYCOLLECTION(:coords) has to be in a string, you need to use CONCAT() to create this string.
$sql = $conn->prepare("
INSERT INTO states(`name`, `poly`)
VALUES(:name,GeomFromText(CONCAT('GEOMETRYCOLLECTION(', :coords, ')')));");

saving information to database from webform

$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW())";
$query = "INSERT INTO address ". "(house_number,street_name,town/city,postcode,province/county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county', NOW())";
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
So I can create a connection to my database no problem and on my previous page I can send username and password to the database but then I come to the user details page to save the information and continually getting Invalid query 2 error. The table names are correct (users & address) and all variables are spelt correctly. Does anyone have a suggestion to fix the issue or a better alternative (I mean to just point me in the right direction of the research I should be looking at if I am way off target, if I have just mispelled something or have something in the wrong place then I would appreciate the heads up, have been at this quite a while now)
This is the code from the previous page and it works fine and sends the information to the database:
$query = "INSERT INTO login ". "(username,password) ". "VALUES('$uname','$epass', NOW())";// sets up sql query
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
mysqli_close($conn); // close database connection
As far as I know all the database side of things is fine, all data types are varchar except for dob which is date (I have tried changing this to varchar to see if it fixed the problem but it didnt) and userID is int and is an autoincrement for the unique primary key. I have also tested the php file without the validation rules and still gives the same error.
Quite a few things wrong here.
First you are reassigning the variable $query; so the first insert will be getting overwritten by the second, you need to concat the variable.
Then you have 2 queries you are attempting to send at one time. However you never tell Sql you've finished your first before starting your second.
Try the following instead take note Of The semi colons ; at the end of each.
You are also putting slashes into your column names which is illegal.
Lastly, you've got more values to insert than you have columns. Remove the now() from the end.
$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email');";
$query .= "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county');";
Although this will now work, I highly recommend you do some research regarding safe practices with Sql.
Here would be a great starting point https://www.w3schools.com/php/php_mysql_prepared_statements.asp
On a side note, why are you concating your Strings? There's no need
$query = "INSERT INTO users (first_name,last_name,dob,mobile_number,landline_number,email) VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW());";
Maybe it's the fact that you are closing the connection after your first call.
try or die(mysqli_error($conn));
EDIT:
Delete passing value "NOW()".
code:
$query = "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county')";

Cant insert data into table but I can update data, dont know whats happenig

this is my first question here and is really dumb.. but I cant get this workig in spite Ive done ir before, dunno if I take the bad pill or what, please help!
Here is my code:
enter code here
<?php
session_start();
include '../conexion.php';
$nombre=$_POST['Nombre'];
$apellido=$_POST['Apellido'];
$mail=$_POST['Mail'];
$telefono=mysqli_real_escape_string($con,$_POST['Telefono']);
$ultimaventa=$_POST['Numeroventa'];
$totalcomprado=0;
$ultimomonto=$_POST['Total'];;
$resultado=mysqli_query($con,"select * from Clientes")or die(mysqli_error($con));
$existe=false;
while($f=mysqli_fetch_array($resultado)){
if($f['Mail']==$mail){
if($f['totalcomprado']==NULL){
$totalcomprado=$ultimomonto;}else{$totalcomprado=$f['totalcomprado']+$ultimomonto;}
mysqli_query($con,"update Clientes SET nombre='".$nombre."', apellido='".$apellido."',Mail='".$mail."',telefono='".$telefono."',ultimaventa='".$ultimaventa."',ultimomonto='".$ultimomonto."',totalcomprado='".$totalcomprado."'")or die(mysqli_error($con));
}else{
$totalcomprado=$ultimomonto;
mysqli_query($con,"insert into clientes(nombre,apellido,Mail,telefono,ultimaventa,ultimomonto,totalcomprado)values(0,
'".$nombre."','".$apellido."','".$mail."','".$telefono."','".$ultimaventa."','".$ultimomonto."','".$ultimomonto."')")or die(mysqli_error($con));}
}
The problema is that the "update part"(when mail is already in database) everything works fine, but when I go to the insert statement nothing happens, nothing inserted, no mysql error, no nothing. All variables have proper values and all data is collected correctly, why i cant insert the data????PS: I tryed putting only the insert statement alone and ye nothing happens...
Your INSERT query has 7 columns in the fields clause, but provides 8 values (note that you have an extra 0 at the beginning of the list of values, which doesn't have a matching column name in the list of fields). It certainly produces an error, you are just not properly catching it.
To quickly fix it, just remove the 0, part in the VALUES clause, but I would recommend figuring out why the error is not seen.
EDIT: and as Josan Iracheta properly pointed out, in MySQL table names are case sensitive, so your table name in the INSERT query needs to begin with a capital letter too.
EDIT2: to be very specific, try this:
mysqli_query($con,"insert into Clientes(nombre,apellido,Mail,telefono,ultimaventa,ultimomonto,totalcomprado)values(
'".$nombre."','".$apellido."','".$mail."','".$telefono."','".$ultimaventa."','".$ultimomonto."','".$ultimomonto."')")or die(mysqli_error($con));}
Also, please note that you have several other problems in your code: your code is vulnerable to SQL injections (try using prepared statements to address it), and also your update query doesn't have WHERE clause, so you update all the rows every time, not just the one that has matching email address.
EDIT4: Now that I looked at your code more closely, your problem not in SQL, it is in PHP -- your logic for running the INSERT query seems to be wrong, you run it if your table has a row with a different email, not if it doesn't have a row with the email you want. Try changing your code like this:
<?php
session_start();
include '../conexion.php';
$nombre=$_POST['Nombre'];
$apellido=$_POST['Apellido'];
$mail=$_POST['Mail'];
$telefono=mysqli_real_escape_string($con,$_POST['Telefono']);
$ultimaventa=$_POST['Numeroventa'];
$totalcomprado=0;
$ultimomonto=$_POST['Total'];;
$resultado=mysqli_query($con,"select * from Clientes WHERE Mail='".$mail."'")or die(mysqli_error($con));
$existe=false;
if (mysqli_num_rows($resultado) == 0) {
$totalcomprado=$ultimomonto;
mysqli_query($con,"insert into clientes(nombre,apellido,Mail,telefono,ultimaventa,ultimomonto,totalcomprado)values(
'".$nombre."','".$apellido."','".$mail."','".$telefono."','".$ultimaventa."','".$ultimomonto."','".$ultimomonto."')")or die(mysqli_error($con));
}
while($f=mysqli_fetch_array($resultado)){
if($f['Mail']==$mail){
if($f['totalcomprado']==NULL){
$totalcomprado=$ultimomonto;}else{$totalcomprado=$f['totalcomprado']+$ultimomonto;}
mysqli_query($con,"update Clientes SET nombre='".$nombre."', apellido='".$apellido."',Mail='".$mail."',telefono='".$telefono."',ultimaventa='".$ultimaventa."',ultimomonto='".$ultimomonto."',totalcomprado='".$totalcomprado."' WHERE Mail='".$mail."'")or die(mysqli_error($con));
}
}
Note that I also added the WHERE clause to the SELECT and UPDATE statements, remove them if it is not what you actually want there. I also did not address all the SQL-injection issues in your code.

PHP MySQL INSERT statement syntax error

I'm having problems with an INSERT statement, and the error only says:
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 '' at line 1
It's not helpful at all.
The version I have tried so far and failed is:
mysql_query("INSET INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
[needless to say that the two variables when printed show the right values]
I've also tried versions with nothing around the table name, with ` or ', a million combinations really and nothing works. Not even with constants or into different tables. It just won't insert anything ever. I've checked the privileges (I'm logging into it with root), and it's all on.
I've tried similar stuff on two different machines with the same server (XAMPP 1.7.7) and it works. I'm completely baffled! What can it be?
Thank you for your time!
First and foremost, just type INSERT correctly.
Using _GET like that really opens you up to SQL INJECTIONS...
Do take a look into MySQL prepared statements.
It is also considered good practice to name the columns that you're inserting data into. That allows you to, latter on, insert extra-columns and keep application logic.
INSERT INTO cos(rowName1, rowName2) VALUES(?, ?)
Where ? would be prepared statements.
Correct:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
Have you tried passing the $link to mysql_query ?
Like:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')", $link);
EDIT:
And of course you must take some security measures before inserting anything into the database, maybe mysql_real_escape_string() or even prepared statements.
You are doing it wrong. Why aren't you escaping the values?
Php.net documentation is providing some good and safe working examples:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
So adapted to your code:
$query = sprintf("INSERT INTO `cos` VALUES (%s, %s);",
mysql_real_escape_string($_GET['prod']),
mysql_real_escape_string($_GET['page']));
$result = mysql_query($query);
Please, always escape your values. And use INSERT, not INSET :)
first this is you are using INSET make it correct with INSERT like
$pro = mysql_real_escape_string($_GET['prod']);
$page = mysql_real_escape_string($_GET['page']);
mysql_query("INSERT INTO `cos` (column1, column2)
VALUES ('$pro', '$page')" );
you forget to set the column names...
Try this:
$prod = $_GET['prod'];
$page = $_GET['page'];
mysql_insert("INSERT INTO 'cos' VALUES('$prod','$page)");
This should very well do it :)

Sql query problem

I have the below sql query that will update the the values from a form to the database
$sql=
"update leads set
category='$Category',
type='$stype',
contactName='$ContactName',
email='$Email',
phone='$Phone',
altphone='$PhoneAlt', mobile='$Mobile',
fax='$Fax',
address='$Address',
city='$City',
country='$Country',
DateEdited='$today',
printed='$Printed',
remarks='$Remarks'
where id='$id'";
$result=mysql_query($sql) or die(mysql_error());
echo '<h1>Successfully Updated!!.</h1>';
when i submit I dont get any errors and the success message is displayed but the database isnt updated . When i echo the $sql, all the values are set properly. and when i ech the $result i get the value 1.
can someone please tell me what am i doing wrong here??
Have you tried running the echo of $sql directly using some DB tool? It may provide a more informative error. Alternatively, if that works you may have an issue where the transaction isn't being committed. Often a connection is set to automatically commit transactions, but that may not be the case here. Try adding a commit.
And have you ever heard of SQL injection attacks?
If you have a query that is not giving the expected result or receiving an error, and the problem isn't obvious, you should generally take a look at the final query just before it's run. Try using this right before running the query:
echo $sql;
exit;
Viewing the actual query often makes it obvious what the problem is, especially when the query includes variables. If the problem still isn't obvious, you can paste the query as is into a query browser to get feedback directly from the database engine.
Interestingly, using parametrized queries, you won't get to see the parameter values, as the parameters get replaced by MySQL, not PHP, however, you'll still get to see the entire prepared query.
Also, you can see the number of affected rows from your UPDATE statement with the mysql_affected_rows() function. You could put this immediately after the query is run:
echo ("Updated records:", mysql_affected_rows());
Spaces are often forgotten when concatenating queries.
$sql = "SELECT * FROM ducks";
$sql .= "WHERE duck = 'goose'";
When echoing the above query, we see:
SELECT * FROM ducksWHERE duck <> 'goose'
I'm guessing that the WHERE clause in your UPDATE statement isn't matching an "id = '$id'".
Also, is the id column really a string? You've put single quotes around the value. MySQL will cast the string to an integer if needed, but if it's an integer, save the database some work and remove the single quotes.
try to echo $sql and run it directly in any database console, may be there is no record with id = $id
SQL Injection can be the answer. Not an intentional attack (at this moment), but if your parameters have some unexpected information like quotes or other reserved characters you can have strange results. So, try to run this SQL directly in your database administration utility.
Try doing this
"""update leads set
category="$Category",
type="$stype", etc...; """
See if that works

Categories