SQL insert not saving to database [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
Im having trouble getting this simple code to work, it,s part of a rating script for a product page.
$connn = new mysqli($servername, $username, $password, $dbname);
if ($connn->connect_error) {
die("Connection failed: " . $connn->connect_error);
}
$vresult1 = mysqli_query($connn,"SELECT * FROM rating_log WHERE ip=$userIP AND product_id=$pid");
if ($vresult1->num_rows > 0) {
// ERROR: user already voted
$v_msg = '<div style="color:red;">You have already voted on this product!</div>';
} else {
// enter vote
mysqli_query($connn,"UPDATE wc_products SET rating=$votecnt1");
mysqli_query($connn,"INSERT INTO rating_log (ip, product_id) VALUES ($userIP, $pid)");
$v_msg = '<div style="color:green;">Thank you for voting! DEBUG['.$userIP.'-'.$pid.']</div>';
}
$conn->close();
} // end rating
All this should do is add a new entry which logs a user ip and the id of the product, then update the product db to register the vote. The update works fine but it wont log the user.

Try this:
$userIP = $mysqli->real_escape_string($userIP);
$pid = $mysqli->real_escape_string($pid);
mysqli_query($connn,"INSERT INTO rating_log (ip, product_id) VALUES ('$userIP', '$pid')");
Single quotes should be used for string values like in the VALUES() list. for more details read this post answer:
When to use single quotes, double quotes, and backticks in MySQL

Related

mysql error occured when displaing the page [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 11 months ago.
working with php and mysql as well. I have following create.php page and need save data to mysql table.
<?php
include "config.php";
if(isset($_POST['submit'])) {
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$gender = $_POST['gender'];
}
$sql = "INSERT INTO 'users' ('firstname','lastname','email','password','gender') VALUES ('$first_name','$last_name','$email','$password','$gender')"; // this is line 12
$result = $conn->query($sql);
if($result == TRUE) {
echo "New record has created successfully";
}
else {
echo "error:" . $sql . "<br>". $conn->error;
}
$conn->close();
?>
but got following error message
Undefined variable: first_name in C:\wamp64\www\simple\create.php on line 12 <br> error:INSERT INTO 'users' ('firstname','lastname','email','password','gender') VALUES ('','','','','') 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 ''users' ('firstname','lastname','email','password','gender') VALUES ('','','',''' at line 1
how to fix this?
You need to put the whole code logic inside the if(isset($_POST['submit'])) condition
What's happening right now is: if there is no $_POST['submit'], your if won't run, thus no variables are declared, but your SQL and rest of the code will still run and that's why it says var not defined
if(isset($_POST['submit'])) { ... }
Coming to the next issue is of using backticks. You really shouldn't have single quotes around the field name. You can use backticks (`) for table and column names, single quotes (') for strings. There is already an answer for it: When to use single quotes, double quotes, and backticks in MySQL

mysqli_query doesnt seem to execute correctly [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
This one has had me stumped for a couple of days. I have a basic PHP script to submit a user registration form. I just cant see what I am doing wrong in this instance the web server is running PHP 7.0 and there are no errors in the logs.
<?php
require_once('connect.php');
if(isset($_POST) && !empty($_POST)){
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =md5($_POST['password']);
$sql = "INSERT INTO 'login' (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $sql);
if($result){
echo "User Rego Secusseflllgk";
}else{
echo "User rego faile";
}
}
?>
I saw a couple of these already but they seemed to be to do with using both myslq and mysqli and others appeared to not be first connection to the DB. Any help would be much appreciated. I am recieving the User Rego Failed echo
You probably want use the backtick ` instead of a single quote ' to wrap your table name.
INSERT INTO `login`
When a query fail, it's useful to print the error message. You can do it with mysqli_error:
echo mysqli_error($connection);
Use table name without single quote and try to check mysqli error with mysqli_error($connection) just after $result.

php mysql cant find id if there is letters inside [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
When i try to search for a available id with numbers, it echos correctly.
HOWEVER, if there is a single letter inside, like this: 5325252T, It wont find it in the database.
I have a column with type: longtext
How can I get around this? I never noticed this problem before and now I'm in a hurry to fix it...
Btw, If i echo all the tables for rusp_9_cf7dbplugin_submits, it also shows those ids with letters inside. Really weird.
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = 5325252T"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["field_value"]."</td><td>".$row["field_value"]." ".$row["field_value"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Just enclose the field_value value in single inverted commas ' since adding a character makes the SQL engine interpret that value as a number where as it is a string literal, whereas if its just numbers then it interprets it as an integer.
Your code becomes...
...
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = '5325252T'"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
...

MySQLi how to check if table exists? [duplicate]

This question already has answers here:
MySQLi Table Exists
(5 answers)
Closed 3 years ago.
I want to create table by app if there's no such table. But doing it for the first time... Need some help, tho
//connecting...
$mysqli = new mysqli($db_params['host'], $db_params['login'], $db_params['pass'], $db_params['name']);
if ($mysqli->query("SHOW TABLES LIKE `products`")){
echo ' YES';
} else echo 'no';
It always says NO.
Read their documentation? https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html Seems like you can do that easily:
CREATE TABLE IF NOT EXISTS `products`
This way you don't have to check first whether a table exists or not, you just create one if it doesn't.
And it seems like you have a syntax error, which is probably the reason why your code keeps returning "no". This should work:
SHOW TABLES LIKE 'products';
Just use single or double quotes, no backticks like `.
You use backticks (`) for table and column names, single (') or double quotes (") for strings, in this case you are giving a string so you should use single or double quotes.
In order to create a table if it not exists, you can use
CREATE TABLE IF NOT EXISTS
Use PHP DESCRIBE statement.
if(mysql_query("DESCRIBE `table_name`")) {
// Exists
}
This solution works for me JUST FINE:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// SQL query
$sql = "SHOW TABLES IN `tests`";
// perform the query and store the result
$result = $conn->query($sql);
// if the $result not False, and contains at least one row
if($result !== false) {
// if at least one table in result
if($result->num_rows > 0) {
// traverse the $result and output the name of the table(s)
while($row = $result->fetch_assoc()) {
echo '<br />'. $row['Tables_in_tests'];
}
}
else echo 'There is no table in "tests"';
}
else echo 'Unable to check the "tests", error - '. $conn->error;
$conn->close();
?>
For a complete and more examples, here the source : http://coursesweb.net/php-mysql/check-table-exists-database_t

Please Check the Update Query is not working. I am new to Mysql please [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
the code is as under.....The Error is Invalid Query. and it is not Updating the table in database. Anyone help please..
<?php
include "connection.php";
$selecteditem=$_POST['salesitem'];
$name=$_POST['name'];
$type=$_POST['type'];
$purchasePrice=$_POST['purchase'];
$salePrice=$_POST['sale'];
$iteminPack=$_POST['nofiteminpack'];
$location=$_POST['location'];
$GenName=$_POST['genric'];
$norcotics=$_POST['radio1'];
$stockinHand=$_POST['stockInHand'];
$conn= mysql_connect("localhost","root","");
mysql_select_db("alkausar",$conn);
$qr2="UPDATE `item` SET name=$name,type=$type,pPrice=$purchasePrice,sPrice=$salePrice,Iteminpack=$iteminPack,location=$location,genricName=$GenName,norcotics=$norcotics,stockInHand=$stockinHand WHERE name='$selecteditem'";
$qr3=mysql_query($qr2);
echo $qr3;
if(!$qr3){
die('Invalid Query:'.mysql_error());
}
?>
You should put all inputs in '
$qr2="UPDATE `item` SET
name='$name',
type='$type',
Price='$purchasePrice',
sPrice='$salePrice',
Iteminpack='$iteminPack',
location='$location',
genricName='$GenName',
norcotics='$norcotics',
stockInHand='$stockinHand'
WHERE name='$selecteditem'";
Depending on what you have in $_POST this could already solve your problem.
If not, echo $qr2 and try to run in the the DB manually and see if you get an error message.

Categories