hey i have a problem with inserting some data in my database:
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
$txn_id = 123456789101234567;
$payer_email = "irgendwas#gmx.de";
$mc_gross = "amount";
$sql = "SELECT COUNT(*) AS count FROM `trans` WHERE `txn_id` = $txn_id";
$q = mysqli_query($mysqli, $sql);
$f = mysqli_fetch_array($q);
if($f['count'] > 0) {
echo "Transaction already processed";
} else {
$insert = mysqli_query($mysqli, "INSERT INTO trans (`txn_id`, `payer_email`,`mc_gross`)
VALUES ($txn_id,$payer_email,$mc_gross)");
if($insert = 1) {
echo "inserted";
} else {
echo "not inserted";
}
}
As a result i get: "inserted", but i have no data in my database..anyone can help me? where is the bug?
edit: this is my table:
define('SECURE', true);
require "connect_to_mysql.php";
$sqlCommand = "CREATE TABLE trans (
id int(11) NOT NULL auto_increment,
txn_id varchar(255) NOT NULL,
payer_email varchar(255) NOT NULL,
mc_gross int(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY (txn_id))";
if ($mysqli->query($sqlCommand)) {
echo "Your trans table has been created successfully!";
} else {
echo "CRITICAL ERROR;".$mysqli->error;
}
The reason you are getting "inserted" is because your if is setting the variable to 1 and is resulting true. Use double equals to compare.
right:
if ($insert == 1)
wrong:
if ($insert = 1)
As far as your sql there seems to be errors with your queries. $txn_id and $payer_email are both varchars which require you to use quotes since it is a string
The string literals in your SQL statement need to be enclosed in single quotes. Your generated SQL text looks like this:
VALUES (123456789101234567,someone#email.de,amount)
But it should really look like this:
VALUES ('123456789101234567','someone#email.de','amount')
^ ^ ^ ^ ^ ^
BTW... when evaluated as an integer, that string literal 'amount' is going to be interpretted as zero.
You should consider using prepared statements with bind variables, instead of including variables in the SQL text. (There are lots of examples of that on StackOverflow.)
To check whether mysqli_query succeeded or not:
$sql = "INSERT INTO ... ";
if ( mysqli_query($mysqli, $sql) ) {
// sql statement executed without error
} else {
// sql statement execution raised an error
}
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
Im trying to take input from a form, then check table (user) if that name exsits and I need to grab the uid colum.
Input (username / MSG) > Check for username > if so get uid > else add user(This I got) > take uid and use when i INSERT the msg into its table (message)
Table structure:
user: uid (Unique) | name
Heres where in at PHP whise:
<?php
$name = $_GET["name"];
$message = $_GET["message"];
$checkn = "SELECT 1 FROM user WHERE name = $name";
$sql = "INSERT INTO user (uid, name) VALUES ('','$name')";
$msg = "INSERT INTO message (uid, message) VALUES ('$uid','$message')";
$uid = "SELECT uid FROM user WHERE name = $name";
$result = $conn->query($checkn);
if ($conn->query($checkn) === TRUE) {
echo "Checkn TRUE";
}else {
echo "<br> SHEEET" . $checkn . $conn->error;
}
$conn->close();?>
I erased the bulk to start over and get this fixed so once I can get this portion done I have the add if user doesn't exist. Thank you.
I think You are writing the query wrong, when using PHP you should write the query inside ' if it contains variable. " won't parse the variable value.
Replace :
$checkn = "SELECT 1 FROM user WHERE name = $name";
With:
$checkn = 'SELECT 1 FROM user WHERE name = $name';
And it should work. Do the same with other queries too. Use ' instead of "
Hope it helps.
Just from the top of my head
<?php
$name = $_GET["name"];
$message = $_GET["message"];
$checkn = sprintf('SELECT 1 FROM `user` WHERE `name` = \'%s\'', $name);
$sql = sprintf('INSERT INTO `user` (`uid`, `name`) VALUES (\'\',\'%s\')', $name);
$msg = sprintf('INSERT INTO `message` (`uid`, `message`) VALUES (\'%s\',\'%s\')', $uid, $message);
$uid = sprintf('SELECT `uid` FROM `user` WHERE `name` = \'%s\'', $name);
$result = $conn->query($checkn);
if ($conn->query($checkn) == TRUE) {
echo "Checkn TRUE";
} else {
echo "<br> SHEEET" . $checkn . $conn->error;
}
$conn->close();
?>
for some reason i have sometimes had problems when i did not put ` around table names.
I have also separated the variable interpolation so it makes it easier to secure it for sql injection (i did not secure it).
You used triple === this means its strict but mysql would pass 1 back which when using strict is not true.
Hope it helps
I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php
<?php
session_start();
$con = mysqli_connect("localhost","root","12369","medical");
$data1 = $_SESSION["symp1"];
$data2 = $_SESSION["symp2"];
$data3 = $_SESSION["symp3"];
$data4 = $_SESSION["symp4"];
$finalData = implode(' ', array($data1, $data2, $data3, $data4));
$userinput = $_REQUEST["answer"];
$dname=$_SESSION["dname"];
$dname = str_replace(' ', '_', $dname);
echo $dname." <br>";
$sql = " UPDATE diseases SET UserInput = $finalData WHERE Name = $dname ";
if($userinput=='yes'){
if(mysqli_query($con,$sql)){
echo "Values inserted";
$_SESSION["info"] = "yes";
header('Location: http://localhost/medical/last.php');
}else{
echo mysqli_errno($con);
$_SESSION["info"] = "no";
//header('Location: http://localhost/medical/last.php');
}
}
?>
I'm getting error 1064? I already read answers to similar question, but my code doesn't work. My table schema is:
CREATE TABLE IF NOT EXISTS `diseases` (
`ID` int(50) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
`Symptoms` varchar(255) NOT NULL,
`Medicines` varchar(255) NOT NULL,
`Description` varchar(255) NOT NULL,
`Tags` varchar(255) NOT NULL,
`UserInput` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
)
What's wrong in my code? Thanks
Change:
$sql = " UPDATE diseases SET UserInput = $finalData WHERE Name = $dname ";
to:
$sql = "UPDATE `diseases` SET `UserInput` = '$finalData' WHERE `Name` = '$dname'";
Add single quotes around variables that contain a string.
Add backticks around columns and table to prevent mysql reserved words error
It would be even better to use mysqli_prepare do the following:
$stmt = mysqli_prepare($con, "UPDATE `diseases` SET `UserInput` = ? WHERE `Name` = ?");
mysqli_stmt_bind_param($stmt, "ss", $finalData, $dname);
mysqli_stmt_execute($stmt);
As the error message should state, you have an error in your SQL syntax:
MySQL Error 1064: You have an error in your SQL syntax
Surround your data by single quotes and you are good to go. Furthermore, Name is a reserved keyword in MySQL. You can still use it in your query, though, but you should consider escaping table names with backticks:
$sql = " UPDATE diseases SET `UserInput` = '$finalData' WHERE `Name` = '$dname' ";
Add single qoutes around your data:
$sql = " UPDATE diseases SET UserInput = '$finalData' WHERE Name = '$dname' ";
or better use prepared statements
I create a table in my database using this code
$con = mysqli_connect($host,$username,$password,$db);
$sql = "CREATE TABLE My_Table(";
for($i = 1; $i<=50 ; $i++) {
if($i!=50)
$sql .= "id_".$i." INT(30) NOT NULL DEFAULT '0',";
else
$sql .= "id_".$i." INT(30) NOT NULL DEFAULT '0')";
}
if (mysqli_query($con,$sql)) {
echo "Done";
}
Now I have $var = 10; and I want to get for example id_10 and change the value of id_10 to id_10+=$var.
I'm a beginner in PHP/MySQL. Thanks in advance.
select:
my $stmt = $con->prepare($con,"SELECT id_".$var." FROM My_table WHERE ...");
$stmt->bind_param($stmt, /* something here which depends on what you need for your condition */ );
$stmt->execute();
update:
my $stmt = $con->prepare($con,"UPDATE My_table SET id_".$var."=id_".$var."+? FROM My_table WHERE ...");
$stmt->bind_param($stmt,"i",$var /* to be changed depending on condition */);
$stmt->execute();
Note that you must make sure that $i is very strictly checked if it comes from the browser ($_GET, $_POST, $_COOKIE...). Otherwise that opens the door to horrible SQL injection errors.
But note my comment above, I don't think this is a good schema.
if ($word != '' && $text != '') {
$result = $conn->query("SELECT * FROM variables WHERE `word` = '$word'");
if ($source = $result->fetch_assoc()) {
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
if ($result = $conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')"))
echo 1;
}
}
The above is the INSERT code (and update) the UPDATE code works fine, however when the INSERT query is called the query returns true but when i check the data, it hasn't been inserted.
Any help is appreciated, thanks in advance.
EDIT:
variables table structure:
`word` varchar(100) NOT NULL, //also PRIMARY KEY
`text` text NOT NULL
You have a single = in an if condition.
maybe you wanted:
if ($result->num_rows){ // see if there are any rows
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
$conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')");
echo 1;
}
tested:
$conn = new mysqli('localhost', 'root', '', 'test');
$word = 'word1';
$text = 'text1';
$result = $conn->query("SELECT * FROM variables WHERE `word` = '$word'");
if ($result->num_rows){
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
$conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')");
echo 1;
}
I've been struggling with the same problem but solved it in a different way.
Check how many rows are affected, like this (this example uses mysqli but I hope you'll get the point):
$number_of_rows_affected = mysqli_affected_rows($conn);
If $number_of_rows_affected = 0 then INSERT wasn't working. A number larger than 0 means a successful INSERT.
Not sure why you use backticks around 'word' and 'text' in your query.
For debugging this, I write the query to a string and print it before executing it, to make sure the query is what I wanted, so use:
$query = "INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')"
print("$query")
if ($result = $conn->query($query))
echo 1;
Are you sure the insert does not work? Do you close your database connection before you check, maybe the results have just not been committed to your database when you check?