Something wrong with data insert - php

Good day,i am trying to insert data into mysql table using php its kinda working but i can't see data in phpmyadmin
<?php
$con=mysqli_connect('localhost','root','');
if(!$con)
{
echo("not connected");
}
if(!mysqli_select_db($con,'exam'))
{
echo 'db not selected';
}
$header = $_POST['header'];
$date = $_POST['date'];
$categ = $_POST['categ'];
$moder = $_POST['moder'];
$posttxt = $_POST['posttxt'];
$theme = $_POST['theme'];
$author = $_POST['author'];
$sql = "INSERT INTO postex (header,date,categ,moder,posttxt,theme,author) VALUES ('$header','$date','$categ','$moder','$posttxt','$theme','$author')";
if
(empty($header) || empty($date) || empty($categ) || empty($moder) || empty($posttxt) || empty($theme) || empty($author))
{
echo "<Br>feel the fields!!!";
}
else{
echo("<br>added,wait for redirect");
}
?>

Ok, before anymore wrong answers come up using mysql_, it's mysqli_query($con, $sql) that wasn't used to execute the query.
RTM http://php.net/manual/en/mysqli.query.php
and take care of that sql injection that you're leaving yourself open to, if/when you go live with this.
https://en.wikipedia.org/wiki/SQL_injection
with a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
while making sure the POST arrays do contain values (and the form uses a POST method with matching named inputs) and that there are no characters passing through that MySQL could complain about, for example: apostrophes.
Escape the data going in, in any respect.
Check for errors via PHP and the query:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
Nota:
You should first check if any of the fields are (not) empty, then execute the query.
I.e. and pseudo conditionals:
if(none empty and good to go){
// execute the query
}
else{
// do something else
}
Plus, if you're using your entire code inside the same file, being the form and php/mysql, then you should check if any of the POST arrays are set/not empty first. That will throw a few errors and give you undesired results.

<?php
function db(){
$servername = "servername";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
$conn->query("SET CHARACTER SET utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
$data=db();
$insert="INSERT INTO movies (bla1, bla2, bla3) VALUES (blavalue1, blavalue2, blavalue3)";
$dotaz=mysqli_query($data,$insert);
if($dotaz){
echo "OK";
}else{
echo "Wrong";
}
?>

Related

How to check whether mysql update query is successful or not?

function insertNewBidPrice($code, $newBidPrice)
{
global $conn;
$sql = "update auctionitem set highestbid=$newBidPrice where code=$code";
//echo $sql;
if($conn->query($sql))
{
return 1;
}
else
{
require 0;
}
}
I have this php fuction that results 0 all time although update query successfully update the table.
I use PDO.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Create a statement object first, using prepare.
$stmt = $conn->prepare($sql);
$worked = $stmt->execute();
if ($worked == TRUE) {
//I did stuff
} else {
// nope
}
function insertNewBidPrice($code, $newBidPrice) {
global $conn;
// write your query
$sql = "UPDATE auctionitem SET highestbid='$newBidPrice' WHERE code='$code'";
// run the query
$result = $conn->query($sql);
// check the result of the query
if ($result == true) {
// it was a success
return 1;
} else {
return 0;
}
}
global $conn;
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
// it worked
}
Here you go this should do the trick. I noticed you say "require 0" in your if else statement it needs to be a return. Other then that i'm not sure on your problem but there are 2 possibilities i can think of.
Your $conn variable is invalid. Check it has the correct credentials, see the $conn->connect_error line, it is in the code i wrote but also here: http://php.net/manual/en/mysqli.connect-error.php.
Possibly the query incorrect. Personally i format everything with capitals ect. as my text editor colors it when i do that and it is easy for me to see what is what. Also there were no quotes surrounding the variables in your SQL statement, this is fine if it is an integer but if you are accidentally passing a string it will fail.
Also check that you have selected the correct table ect. in your SQL.

SQL insert to MySQL doesn't work

I'm currently trying to insert username, pw to a DB, and check if the username already exists.
The problem is that the SQL (select) syntax doesn't work, nor does the (insert). I've checked around for a couple of hours in forums and Stackoverflow, and my current code is the following.
What might be the problem?
Thanks, Jimmie.
<?php
$servername = "localhost";
$username = "name";
$password = "pw";
$dbname = "dbaname";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ((isset ($_POST["identity"])) && (isset ($_POST["pin"])) && (isset ($_POST["token"])))
{
$identity = htmlspecialchars($_POST['identity'], ENT_QUOTES, "ISO-8859-1");
$pin = htmlspecialchars($_POST['pin'], ENT_QUOTES, "ISO-8859-1");
$token = htmlspecialchars($_POST['token'], ENT_QUOTES, "ISO-8859-1");
echo "$identity";
if($token == "xyz13D;A##:!#")
{
$result = $mysqli->query("SELECT `identity` FROM Users WHERE `identity` = '" . $identity . "'");
if($result->num_rows == 0)
{
echo "successCreat";
// Perform queries
mysqli_query($mysqli,"SELECT * FROM Users");
mysqli_query($mysqli,"INSERT INTO Users (identity,pin,userActivity, identityCreated) VALUES ('$identity', '$pin',1,now())");
}
else
{
echo "failureCreate";
}
}
else
{
echo"Wrong Key";
}
}
$mysqli->close();
?>
Assuming that identity is a primary key, then you can check the error flags after executing an INSERT query to see if an error occurred.
mysqli_query( $mysqli, "INSERT INTO ... " ); //< ... Represents query
if (mysqli_error( $mysqli )) {
echo "Failure";
}
else {
echo "Success";
}
Also, you should properly escape input as stated in the comments. In addition, you should check whether or not the connection attempt was successful using mysqli_connect_error.
Finally, there might be an issue in your SQL suntax which mysqli_error will also catch. A last possibility is that the POST data isn't being set properly and the code is being ignored completely.

$_GET not inserting into MySQL database

I have a small PHP script which I would like to use to add a value to an SQL table.
When I do something like: http://ipaddress/phptest.php?350
If I just put 350 into the insert statement, it works fine. I have tried to get the result of GET to be added but seem to be unable to after many attempts.
I either get a blank, or "array" added to my table.
Any help would be appreciated.
Also how would I add two values? phptext.php?350&?450 for example?
Thanks
<?php
$servername = "localhost";
$username = "administrator";
$password = "blabla";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print_r($_GET);
if($_GET["a"] === "") echo "a is an empty string\n";
if($_GET["a"] === false) echo "a is false\n";
if($_GET["a"] === null) echo "a is null\n";
if(isset($_GET["a"])) echo "a is set\n";
if(!empty($_GET[a])) echo "a is not empty";
$sql = "INSERT INTO test.sensor (VALUE) VALUES ('$_GET["a"]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The HTTP specification declares that GET variables are passed like the following example:
url.com/?bar=value&foo=value
So technically you're passing the GET values wrong. As I see, the correction would be:
http://ipaddress/phptest.php?a=350
Also, as an extra pointer, sanitize your variables before submitting to a SQL database, as it will lead to SQL injection vulnerabilities.
You might want to use...
mysqli_real_escape_string();
Or use prepared statements, the more accepted/fail-safe way of working with them.
For more reference,
http://php.net/manual/en/mysqli.real-escape-string.php

PHP MySQL if row exists not doing anything

I am trying to get this piece of code to check if the line already exists in the database.
These lines get inserted into the database:
512150 # Merlinz is banned permanently by SO_Conner. # banned untill never for RDM
Now this piece of code checks if it already exists in the DB, if it doesn't exist we insert it.
$search = "permanently";
$logfile = "ban_list.txt";
$timestamp = time();
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search))
{
$check = mysql_query("SELECT * FROM `pincodes` WHERE `Pincode` = '$pincode' ");
if(mysql_num_rows($check) == 1) {
die(); }
else
{
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(stristr($line,$search))
$sql = "INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
// case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
}
Like I said, it is still inserting it into my Database even though the line is present in the database.
Thanks }
if(mysql_num_rows($check)>0) {
echo " ";
}
else
{
change your line of code to this,
this would check if it already exist.
Flies Away
Try checking in the following manner
if(mysql_num_rows($check) !== FALSE)
Also try printing the query to see how the value is embedding for debugging purpose...
If it's a ban list based on a unique username why not alter the table to make the column unique. This code will also delete duplicates in the column 'Ban'.
ALTER IGNORE TABLE ingamebanlist ADD UNIQUE (Ban);
Next, mysql_num_rows() is deprecated in php 5.5
http://php.net/manual/en/function.mysql-affected-rows.php
Your best bet (even if your mysql functions work) is to change the mysql function calls to mysqli function calls. They are more secure and up to date.As well as making sure there is a constant in your code so your not switching between them.
If you change the mysql commands to mysqli this should work.
mysqli_affected_rows($conn);
Lastly, if you change the 'Ban' column to unique and make use of the mysqli_affected_rows this code should be all you need to insert when doesn't exist.
mysqli_query($conn,"INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')");
$num = mysqli_affected_rows($conn);
if($num > 0)
{
echo "Successfully Inserted";
}
else if($num == 0)
{
echo "Line already exists";
}
else
{
echo "Insert Error";
}

PHP error in mysql database selection

I wrote a code in PHP to connect with Mysql database and add data into it.. code is given below:
$dbhostname = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "rms_invoice";
function showDBMessage(){
if($_POST["name"] != NULL){
//came from register page
if(register()){
print("<br/>Registered successfully!!!");
} else {
print("<br/>Registration failed!!!");
}
}
}
function register(){
global $dbhostname,$dbusername,$dbpassword,$dbname;
// Create connection
$con=mysqli_connect($dbhostname,$dbusername,$dbpassword);
// Check connection
if (!mysqli_connect_errno()) {
print("MYSQL Connection established...<br/>");
echo "<br/>Successful: ".mysqli_get_host_info($con);
$selected = mysqli_select_db($con, $dbname);
if(false!==$selected){
$name = mysqli_real_escape_string($con, $_POST["name"]);
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$address = mysqli_real_escape_string($con, $_POST["address"]);
$insertUserQuery="INSERT INTO USER(name,username,password,address) VALUES ('$name','$username','$password','$address')";
echo $insertUserQuery;
$result = mysqli_query($con, $insertUserQuery);
if ( false===$result ) {
printf("<br/>mysqli_connect_error: %s\n", mysqli_connect_error());
printf("<br/>mysqli_error: %s\n", mysqli_error($con));
} else {
echo "<h4>New User Added!!!</h4><br/>";
return true;
}
}else{
printf("<br/>Error while selecting database, error:%s\n",mysqli_errno($con));
}
} else {
print("<br/>Failed to connect to MySQL: "+mysqli_connect_error());
}
mysqli_close($con);
return false;
}
and the output is:
MYSQL Connection established...
Successful: localhost via TCP/IP
INSERT INTO USER(name,username,password,address) VALUES ('nitin','ndthokare','p','beed')
mysqli_connect_error:
mysqli_error: No database selected
Registration failed!!!
It is getting connected but database selection seems to be problem. (same query executes successfully through mysql cli).
I tried many possible corrections in code discussed on SO, but could not succeed.
Can anybody help me to find out the mistake?
if(false!==!$selected){
is extremely unusual operator (called "double negative") means you want to execute the following code block only if $selected is FALSE.
to make it much less confusing, write it without all these magic chants
if($selected){
or even omit this useless check completely.

Categories