Not adding values to database - php

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.

Related

SQL Query of checking existing entry in database is not working

<?php
error_reporting(0);
$link = mysqli_connect("localhost", "root", "", "checksql");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$myemailaddress=$_POST['useremail'];
$mypassword=$_POST['userpassword'];
$sql = mysqli_query("SELECT * FROM register WHERE Email = '$myemailaddress' ");
$count = mysqli_num_rows($sql);
echo $count;
if($count > 0){
echo "success";
} else{
echo "failed";
}
?>
I am trying to check whether an email exists in the database or not. I searched different thread on stackoverflow and tried to correct it but failed. Even the echo of $count isn't showing it's value. Is there any other way to check it?
You didn't pass db connection to your query
$sql = mysqli_query($link, "SELECT ...
^^^^^^
Btw, your code is open to SQL injection.
Use a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
More on SQL injection:
https://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/en/security.database.sql-injection.php
How can I prevent SQL injection in PHP?
Also make sure your POST arrays are not failing you.
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: Displaying errors should only be done in staging, and never production.
error_reporting(0); doesn't help you, it turns it off.
Add or die(mysqli_error($link)) to mysqli_query() to check for errors.
http://php.net/manual/en/mysqli.error.php
Your form should be using a POST method with name attributes for both your POSTs. That is unclear and wasn't posted in your question; call it an insight.
If you are using both your form and PHP/MySQL inside the same file, then that will trigger undefined index notices on initial page load.
Use !empty() for them.
Reference(s):
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/function.empty.php

Get Results from mySQL in PHP

I am trying to get result from as table in mySQL in the following code.
It does not work. I am newbie in PHP.
Maybe someone can help whatws wrong in my code? I think that my SQL sentence is not written well. Is it?
<?php
header("Content-type: text/html; charset=utf8");
// header('Content-Type:text/html;charset=utf-8');
//1. create connection
$connection=mysql_connect("localhost","user","pass");
if(!$connection){
die("database connection failed:" . mysql_error());
}
//2. select database
$db = mysql_select_db("database",$connection);
if(!db) {
die("database connection failed:" . mysql_error());
}
//if i want to work with hebrew databases
mysql_query("SET NAMES 'utf8'",$connection); // reading heberer from phpadmin database - only for hebrew sites
$MessageNo = $_POST['MsgNo']
//$MessageN0=(int)$MessageNo
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;
$messages = array();
while ($row = mysql_fetch_array($query)) {
$messages[] = array('MsgContId' => $row['MsgContId'], 'MsgNo' => $row['MsgNo'],'MsgContent' => $row['MsgContent'], 'AddedBy' => $row['AddedBy'],'AddedAt'=>$row['AddedAt']);
}
// echo json_encode(array('users' => $users));
echo json_encode($messages);
mysql_close($connection);
?>
I can see on this line you have formatting errors:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;
Remove the extra two semi-colons:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");
Also this:
$MessageNo = $_POST['MsgNo']
Needs a semi-colon:
$MessageNo = $_POST['MsgNo'];
Additionally you're using deprecated functions. I would suggest you look into MySQLi functions or PDO.
Consult: mysqli with prepared statements, or PDO with prepared statements.
EDIT: Also in your second query, you're not using the connection string:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'",$connection);
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.
Also add or die(mysql_error()) to mysql_query().
Sidenote:
Your present code is open to SQL injection.

how to insert value from radio button into mysql using php

i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

Why is my database table not updated after this query?

I am using a dedicated server through 1 and 1 and the PHP code as below will not insert the data into the database.
All connections to database are correct.
$id = $_REQUEST['id'];
$content = $_REQUEST['content'];
mysql_query("UPDATE `content` SET `content` = '$content' WHERE `id`='$id'");
When I test on my local server all works fine, there is something about the server that will not allow me to upload. I am connecting using a very general method
$connection = mysql_connect("localhost",
"root",
"password");
mysql_select_db("dbname", $connection);
1) Turn on error reporting by putting this on the top of your PHP script:
error_reporting(E_ALL);
2) Run your script. Any errors? If yes, proceed according to the error message you get.
3) Double check that your variables are actually defined (you are getting them from the request, you cannot be sure request actually contains values you are trying to use).
4) Your SQL query is very dangerous. Use mysql_real_escape_string() or prepared statements. Don't put quotes around integer values.
5) Edit your script to look more like this:
error_reporting(E_ALL);
$id = (isset($_REQUEST['id']) && !empty($_REQUEST['id'])) ? $_REQUEST['id'] : NULL;
$content = (isset($_REQUEST['content']) && !empty($_REQUEST['content'])) ? $_REQUEST['content'] : NULL;
try{
if(NULL === $id){
throw new Exception('$id is NULL');
}
if(NULL === $content){
throw new Exception('$content is NULL');
}
$id = mysql_real_escape_string($id);
$content = mysql_real_escape_string($content);
$sql = "UPDATE content SET content = '$content' WHERE id = $id";
// connect to database
// ...
mysql_query($sql);
}catch(Exception $e){
echo '<p style="color: red;">',$e->getMessage(),'</p>';
}
Ddebugging for beginners...
You haven't posted any errors, is error reporting turned off? Debugging is much easier with error reporting turned on.
error_reporting(E_ALL);
We'll also want to see what the actual query we're trying to run in the database. Perhaps the variables haven't been properly escaped (Contains illegal characters).
$query = "UPDATE table SET name='$name' where id='$id'";
echo $query;
mysql_query($query);
My guess is that you have to mysql_real_escape_string(); both variables.
Also you pass $id as a string, it's probably an integer.
You're mishandling transactions.

Categories