Can't get form data to post using mySQLi - php

Almost identical to a previous question however I am now trying to use mySQLi to record some form data.
After I submit, the data does not post to the table. I've been reading through to the mySQLi documentation and some different videos but I can't figure it out.
Thanks in advance!
<?php
include('config.php');
if (
isset($_POST['store_id']) &&
isset($_POST['item_title']) &&
isset($_POST['date']) &&
isset($_POST['price'])
)
{
$store = get_post('store_id');
$item = get_post('item_title');
$date = get_post('date');
$price = get_post('price');
$query = "INSERT INTO ebay_data VALUES('".$store."', '".$item."', '".$date."', '".$price."')";
$input = $db_mysqli->query($query);
}
?>

You want to make sure your config is actually connecting of course. I typically just go to do it on one page if I get stuck, either way try:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', my_databasename);
/* check connection */
if (mysqli_connect_errno()) {
printf('Connect failed: %s\n', mysqli_connect_error());
exit();
}
$query = 'INSERT INTO ebay_data VALUES($store, $item, $date, $price)';
$mysqli->query($query);
printf ('New Record has id %d.\n', $mysqli->insert_id);
/* close connection */
$mysqli->close();
See if you get anything out on the page. Also should double check your post values are not empty. I have also ran into weird problems where setting the post to a var messed up sql queries, maybe try:
if (isset($_POST['store_id']) && isset($_POST['item_title']) && isset($_POST['date']) && isset($_POST['price']))
{
$query = "INSERT INTO ebay_data VALUES($_POST['store_id'], $_POST['item_title'], $_POST['date'], $_POST['price'])";
...
You also 100% need to check those post values, keeping your database and users safe. Prepared statements is a start. You do need a lot more than that though to keep it safe...
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Related

Not adding values to database

I just created ajax function which sends data to php and php to database. Inserting to dotp_task_log table, works fine. But further, when I need to add data to dotp_tasks after adding to dotp_task_log, it isn't adding, and I cant find why... I get the Gerror, Here is my php file which adds data to database.
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task) VALUES ('$currentUser' , '$currentTasken')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("INSERT INTO dotp_tasks (task_percent_complete) VALUES ('$currentPercent') WHERE task_id='$currentTasken'" ) ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
As I stated in comments:
INSERT... doesn't have a WHERE clause. Error checking would have signaled the syntax error. INSERT ON DUPLICATE KEY does. You may have wanted to use UPDATE instead
$inss = mysql_query("UPDATE dotp_tasks
SET task_percent_complete = '$currentPercent'
WHERE task_id='$currentTasken'" );
References:
https://dev.mysql.com/doc/refman/5.0/en/update.html
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
Plus, do use error checking when testing:
http://php.net/manual/en/function.mysql-error.php
instead of echoing custom messages.
Add or die(mysql_error()) to mysql_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Make sure your HTML form does hold a POST method and that all inputs bear the name attributes and no typos. Using error reporting, will signal that.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Fred -ii- nailed it in his comment - you're using improper syntax in that query.
It looks like you want an update query, for example:
update dotp_tasks
set task_percent_complete = '$currentPercent'
where task_id = '$currentTasken'
Additionally - it's always best to avoid creating queries by formatting strings manually - you'll want to look into prepared statements to improve this code further.

PHP - MySql Database info not storing

I have been trying to figure this out for hours, I have created a database ( MySql/PHPMyadmin) and i am trying to get user input stored to be able to call back up, however the info is not making it/ saving it to the database, everything shows up okay except this part of code:
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
when run gives me a display of -1 row, I believe this to be a big part of the problem as everything else seems to work okay. I am a complete beginner so could you guys tell me how the best way of debugging this is.
$dbc = $dbc = mysqli_connect ($hostname, $username, $password, $dbname) OR die("Could not Connect");
To input the data to the db i have the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$comments = $_POST ['Comments'];
if (!empty ($comments)){
include ('mysqldb.php');
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
}else {
echo "Nothing Submitted";
}
}
The line:
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
should be:
mysqli_query ($dbc,"INSERT INTO `User-Comments` (Comments) VALUES ('$comments')");
Notice the change in the apostrophe character ( ` ) around your table name.
An excerpt from the documentation for function mysqli_stmt_affected_rows(): -1 indicates that the query has returned an error.
You should check the value returned by mysqli_query(). If it returns FALSE then you can get details about the reason (error message) by using function mysqli_error().

mysqli migration issue and security advices

I tried to migrate from mysql to mysqli but this code doesn't work. I'm new to php and mysql
$link = mysqli_connect("localhost", "user", "password", "db");
/* check connection */
if (mysqli_connect_errno()) { printf("Connect failed: %s\n",
mysqli_connect_error()); exit(); }
if ($result = mysqli_query($link, "SELECT * FROM users WHERE uid='$uid'")) {
if(mysqli_num_rows($result) != 0) {
mysqli_query($link, "UPDATE users SET array='$array' WHERE uid='$uid'");
}
else {mysqli_query($link, "INSERT INTO users (uid,array) VALUES ('$uid','$array')"); }
mysqli_free_result($result); }
/* close connection */
mysqli_close($link);
?>
So my questions are:
what should be changed to make this code work;
what security vulnerabilities does this code have and what changes in the code would you suggest to fix that?
Thanks for spending time to answer my questions.
You need to set error reporting to maximum level and make error messages available. this way you will let PHP to tell you what is going wrong and what needs to be fixed.
however, sometimes our code still doesn't work yet there are no error messages around. it's time to do some debugging
You have to change this code to make every variable to go into query via placeholder only
however, raw mysqli is extremely bad with prepared statements, so, I would recommend not to use it but rather move toward PDO or safeMysql. A latter one will let you to have safe queries with the same amount of code.
if ($db->getOne("SELECT 1 FROM users WHERE uid=?i",$uid))
{
$db->query("UPDATE users SET array=?s WHERE uid=?i",$array,$uid);
} else {
$db->query("INSERT INTO users (uid,array) VALUES (?i,?s)",$uid,$array);
}
By the way, Mysql lets you to make all these three queries in one:
$sql = "INSERT INTO users (uid, array) VALUES (?i,?s)
ON DUPLICATE KEY UPDATE array=values(array)";
$db->query($sql, $uid, $array);

Logging $_SERVER to mysql

I use this code , to log $_SERVER['REMOTE_ADDR']; to my small db
my issue is value never saved to db , cant figure what i missed in the code
Any tips ?
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs(REMOTE_ADDR,) VALUES ('$ip')";
}
echo $_SERVER['REMOTE_ADDR'];
?>
This should work. In addition to the other comments here, you had a comma (,) too much in your query.
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs (REMOTE_ADDR) VALUES ('$ip')";
mysql_query($sql);
}
initCounter();
?>
You aren't actually executing the query. You create the SQL but don't use mysql_query($sql)
You have a comma at this point in the SQL REMOTE_ADDR, <-- remove that
When you execute the query, use mysql_error() to test for an error message (and check the result of mysql_query() for a boolean false.
Finally I would suggest switching to MySQLi or PDO.
If that's you're full code... there is one thing missing you actually need to EXECUTE the query...
mysql_query($sql);
EDIT:
I have just noticed, you're connecting to the DB OUTSIDE of the function trying to run the Query... obviously it will fail as inside the function, it has no awareness of the DB connection.

MySQL not saving sentence after an '

This one has got me stumped. When I try to save something to the database that contains an apostrophe ('), it will save the sence up until then and after that it does not not. For example;
Say I am trying to save this: Report details Tim Cook's changes at Apple, for better or worse ยป
It saves: Report details Tim Cook
It saves to the database fine but only everything before the '
My code:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Any help as to why it might not be saving properly? I have tried mysql_real_escape_string but (if I am using it correctly) that does not seem to work.
Side note: What is the best way to secure the form above from attacks?
Update It is also doing it for " as well.
You need to call mysql_real_escape_string() after connecting to your database:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Change
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
to
$query = "INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')";
echo $query;
mysql_query($query);
And check out the actual query you are sending, easy to spot the problems then :)

Categories