No errors, sql is right, table doesn't update - php

I'm trying to update my database via a simple form and for some reason, the table doesn't update. I tried the sql query inside phpmyadmin and it seemed to work fine.
<?php
include("_/inc/session_handler.php");
include("_/inc/dbcon.php");
$uplform = "";
if(isset($_POST['insert'])){
$post=$_POST['wish'];
$succes="";
$succes .="<h1>SUCCES</h1>";
$insert_wish_sql="INSERT INTO wishlist(wish_id, wish, datetime)VALUES (null, '$post', CURDATE())";//insert new post
echo $succes;
}
//The form
$uplform .="<form action=\"\"method=\"post\">";
$uplform .="<input type='text' name='wish' placeholder='wish'/>";
$uplform .="<input type=\"submit\" name=\"insert\" value=\"Upload\" />";
$uplform .="</form>";
?>
i even get the succes message, but nothing happens in the table. what am i missing?
UPDATE:
I just went fully retarded. i forgot to add
$link = mysql_connect($host, $login, $pw);
mysql_select_db($database);
so i was basically not connected to the database 8-|.
Thanx a lot!

I miss your connection to a database server ( I guess its' that include) and finally if a connection exits, you need to send/execute your query.
The API's: PDO or mysqli is good for it.
or to test stuff, with the mysql API ( but I would not recommend it to use it live)
http://ch1.php.net/manual/en/book.mysql.php

There may be one problem looking at your code is that it is not executed. SO execute it like this
$res = mysqli_query($conn, $insert_wish_sql);
But the bigger concern is your sql itself as you are passing null as the value for id. Is your id is not primary or auto increment. If it is then it will fail always.

Related

Why is my Select Statement not working properly?

I am trying to select rows in my table sql. I have done this many times and for this instant it wouldn't work.
Displaying the variable $id, displays correct value, which means it receives a correct value from $_POST however after using it on Select Statement and using mysql_fetch_array, nothing displays.
my code
$id=$_POST['idsend'];
$edit = mysql_query("SELECT * FROM students WHERE id= '$id'") or die(mysql_error());
$fetch=mysql_fetch_array($edit);
echo 'ID= '.$id; ---------> This one displays properly
echo 'ID= '.$fetch['id']; --------> displays nothing
Please help me find out what's wrong. Hehe thanks in advance.
It would be safer to use PDO, to prevent SQL Injection (I made a PDO example of your query):
// it's better to put the following lines into a configuration file!
$host = "enter hostname here";
$dbname = "enter dbname here";
$username = "enter db username here";
$password = "enter db password here";
// setup a PDO connection (needs some error handling)
$db_handle = new PDO("mysql:host=$host;dbname=$dbname;", $username, $password);
// prepare and execute query
$q_handle = $db_handle->prepare("select * from students where id = ?");
$id = $_POST["idsend"];
$q_handle->bindParam(1, $id);
$q_handle->execute();
// get stuff from array
$arr = $q_handle->fetch(PDO::FETCH_ASSOC);
echo $arr["id"];
First of all, you shouldn't use mysql_* functions anymore.
You code fails because mysql_fetch_array() only returns a resource, you need to loop over it to get the actual result.
while ( $row = mysql_fetch_array( $edit ) ) {
printf( 'ID: %s', $row['id'] );
}
Okay, I have found out what's wrong. I apologize for disturbing everyone. I have realized what's wrong in my code and you won't find it on the code I posted in my question.
Carelessness again is the cause for all these. :) hehe
This is where the error is coming from
<form action="" method="post">
<input type="hidden" name="idsend" value="' . $row['id'] . '"/>
I have assigned a variable on a value with extra spaces/character? So the code must look like this.
<input type="hidden" name="idsend" value="'.$row['id'].'"/>
It must be assigned properly to work smoothly with the select statement.
I guess echo-ing the values isn't enough to see if there's something wrong.
Sorry for the trouble.

UPDATED:[MySQL won't update in Where condition PHP]

I just updated this question.
I can't seem to update my database whenever I am putting variable $ecode on my WHERE condition. But when I echo this variable it always echoes its right value.
<?php
require 'sqlicon.php';
$q=$_GET['q'];
$ecode= $_GET['ecode'];
echo"".$ecode;
$result=$db->query("UPDATE offset_form SET Approved='".$q."' WHERE Employee_Code='".$ecode."'");
?>
this is the content of sqlicon.php:
<?php
$db=new mysqli('localhost','root','',dbuser'); //localhost,username,password, dbname
?>
This is where I am getting the date for $q and $ecode: Sorry if it haven't been in mysqli yet.
testingjava.php:
<html>
<title> Offset Requests </title>
<head><link rel="stylesheet" type="text/css" href="up.css"/></head>
<script>
function Approval() {
var name;
name=document.getElementById('ename').textContent;
if(document.form1.approval[0].checked true) {
alert(name);
window.location.href = "sqli.php?q=Yes" + "&ecode=" + name;
}
}
</script>
<body>
<form id="form1" name="form1" method="post" action="testingjava.php">
<?php
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("dbuser",$conn);
$query=mysql_query("Select * from offset_form where Approved=''");
while($fetch=mysql_fetch_array($query)) {
$ecode=$fetch['Employee_Code'];
//$_SESSION['ecode']=$ecode;
$ename=$fetch['Employee_Name'];
$epos=$fetch['Employee_Position'];
$edpt=$fetch['Employee_Department'];
$dleave=$fetch['Date_Leave'];
$dreturn=$fetch['Date_Return'];
$reason=$fetch['Offset_Reason'];
echo "".$ecode ."".$ename." ".$epos." ".$edpt." ".$dleave." ".$dreturn." ".$reason;
echo "<input type='radio' name='approval' onChange='Approval()'>Yes";
echo "<input type='radio' name='approval'>No";
echo "<input type='text' name='remarks' size='30'>";
echo"<hr id='br'></hr>";
echo"<input type='submit' value='Submit' name='send' onClick='Approval()'>";
}
?>
</form>
</body>
</html>
I am only testing to manipulate my database when I triggered a radio button.
1) you should be using mysql_real_escape_string($_GET[]) or someone with inject a mysql command into you system like DROP TABLE which will be the end of your database.
2)secondly I would move over to using PHP PDO it is more secure and it is faster (by a long way).
3) change your scond to last line from
mysql_query($sql,$conn);
to
mysql_query($sql,$conn) or die(mysql_error()." _____is the string correct? ".$sql);
then is should echo out any errors, if you post the echoed error we can probably fix it
having looked at it I am guessing the problem is you have missed the .. around the $q, so the $sql contains the string "$q" rather than the string assigned to the variable $q
try this
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
try this way..
$sql=("update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
always try to echo your query and see what's going wrong with your query..
if password is set to your dbms the provide the third param passwrod
$conn = mysql_connect("localhost","root","<passwrod>");
or you can leave it blank if passwrod is not set.
and try this
$sql="update offset_form set Approved =$q where Employee_Code=$ecode";
or
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'";
note: double quotes will parse the php variable ,
most probably there is problem in the manner of quotes you are using.
are you should your query is what you want?
One thing that is confusing is the fact that you have this commented out:
"INSERT INTO offset_form (Approved) VALUES ('".$ecode."')"
And then you have this as your update:
"UPDATE offset_form SET Approved = '$q' WHERE Employee_Code = '".$ecode."'"
The values you are using don't tally together. Surely you should have:
"UPDATE offset_form SET Approved = '$q' where Approved = '".$ecode."'"
This is because you are inserting $ecode into the column Approved, but then searching for $ecode in another column called Employee_Code. Perhaps you need to modify your insert statement instead? Either that or $ecode could be just representing two different values at different times?
quotes
The only way switching quotes will make a difference is if your embedded values contain quotes themselves. In which case using the correct escape function will sort the problem. So you are free to use either:
"UPDATE offset_form SET Approved = '$q' where Approved='$ecode'"
or:
"UPDATE offset_form SET Approved = '".$q."' where Approved = '".$ecode."'"
or:
'UPDATE offset_form SET Approved = "'.$q.'" where Approved = "'.$ecode.'"'
but not:
'UPDATE offset_form SET Approved = "$q" where Approved = "$ecode"'
either of the first three should not make a difference.
further things to do
backticks
As a rule I always write my queries escaping table and column names using backticks, just to make sure I'm not accidentally using a reserved word:
"UPDATE `offset_form` SET `Approved`='$q' WHERE `Employee_Code`='".$ecode."'"
double check your dataset
Make certain that the same query you are trying to run in PHP, works inside your dbms. This involves echoing the query out in PHP and then executing it via PHPMyAdmin, Navicat, or whatever you use to access your database outside of coding. For example, a query with hard-coded values, if this doesn't work you have a logic problem in your query or database design that has nothing to do with PHP:
"UPDATE offset_form SET Approved='13' WHERE Employee_Code='12'"
check your white space
Sometimes queries that seem they should be working are having problems because your column values contain accidental invisible white space. If so, they would only be selectable using something like:
"UPDATE offset_form SET Approved='$q' WHERE Employee_Code LIKE '%".$ecode."%'"
check user privileges
Make certain your MySQL user has the ability to perform the type of query you are attempting, this means allowing SELECT, INSERT and UPDATE queries.
disclaimer
As others have already stated, you should upgrade to non deprecated database access methods. If not, you should at least be using mysql_real_escape_string to better protect against malicious intent.
Please debug the value of $q and try to run this code:
session_start();
$q=$_GET['q'];
$ecode=$_GET['ecode'];
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("asiantech",$conn);
echo"".$ecode;
echo"<br>".$q;
$sql="update offset_form set Approved ='".mysql_real_escape_string($q)."' where Employee_Code='".$ecode."'";
//$sql = "INSERT INTO offset_form (Approved) VALUES ('".$ecode."')";
mysql_query($sql,$conn);

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Heavy issue here trying to upload data to a database

I'm having a big issue here, I'm trying to upload some data to a database, and I really don't have a clue why it isn't getting uploaded.
This one here is my HTML form to send data to the php. (This one here should have no problem at all)
<form method="post" action="uploadinfo.php">
<div style="width:542px;height:129px;margin-left:45px;margin-top:102px">
<textarea name="stufftoupload" placeholder="Write your stuff here" rows="8" cols="65"></textarea>
</div>
<div style="width:95px;height:29px;margin-left:489px;margin-top:22px">
<input type="image" src="myimg.png">
</div>
</form>
And this one here is my PHP to upload to the database, this is where the problem should be, but I have no clue what it is. I've tried several solutions, but nothing is working.
<?php
session_start();
$db = mysql_connect("host","db","pass");
if(!$db) die("Error");
mysql_select_db("table",$db);
$email = $_SESSION['email'];
$stuff = $_POST['stuff'];
if (!$stuff)
{
echo "<script type='text/javascript'>window.alert('Fill all the blanks.')</script>";
$url = 'upload.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
else
{
$url = 'success.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
mysql_query('SET NAMES utf8');
$sql = "SELECT * FROM table WHERE email = '$email'";
$result = mysqli_query($db,$sql);
mysqli_fetch_all($result,MYSQLI_ASSOC);
$sql = "INSERT INTO table SET stuff = '$stuff'" or die(mysql_error());
$result = mysql_query($sql);
?>
So this is about it, I'm almost positive it's something within this code, but it could be some bad session managing, though I'm not totally sure about it.
Anyway, thanks in advance for the help. It'll be totally appreciated.
$db is connecting to the database using the mysql method, but you are querying based on the mysqli methods. There are 2 things you need to do here to have an idea of what is going on. Firstly, change all your mysql_ calls to mysqli_ calls, and add some error reporting (so for example adding or die (mysqli_error($db); to the end of every line where you query) should point you in the right direction.
Your first glaring problem here is that you conneced to the DB using mysql_connect, but are then trying to query that connection using mysqli. Use one, not both.
Also, your SQL Query should read INSERT INTO table (stuff) VALUES ($stuff) rather than INSERT INTO table SET stuff = '$stuff'
There are a few problems here so I'll start with what I see now.
This line:
$db = mysql_connect("host","db","pass");
is what connects to your database and I'm assuming that "host" doesn't point to anything. Depending on where that is running, normally Localhost is used. You would also need to make sure the password is correct.
As suggested, use mysqli.
Your insert needs to be something like:
INSERT INTO table VALUES ({$stuff});
Not sure what you want from that form but your session variables will have to match the input names you use on the form.
$stuff = $_POST['stufftoupload'];

MySQL/PHP update query not executing

I tested the variables in the update statement and checked if a database connection is established, however the query doesn't run, can you please show me the error in my code.
for($i=0; $i <= $numcourses; $i++){
echo '<div class="new'.$i.'" id="new'.$i.'"><label>'.$course_names[$i].'</label>
<input name="edit'.$i.'" type="submit" value="Edit" /><input name="delete'.$i.'" type="submit" value="Delete" /><br /></div>';
$name="edit".$i;
if (isset($_POST[$name])){
echo '<input name="text" type="text" value="'.$course_names[$i].'" /><input name="save'.$i.'" type="submit" value="Save"/>';
}
$name2="save".$i;
if (isset($_POST[$name2])){
include "includes/open.php";
$newname=($_POST['text']);
$int=$i+1;
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
mysql_query($query) or die(mysql_error());
include "includes/close.php";
}
}
Update: Thanx Marc B, adding or die(mysql_error());showed me the error in my code, everything works again and I'm back on track.
You have no error handling on your query calls:
mysql_query($query) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
which would tell you if there's any problems with the query execution. On a meta level, you're wide open to SQL injection attacks, so you'd better read up about that and fix the problem before you go any further with your code.
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
is cID an integer ? in the update statement, looks to me like a string, try to echo every query and check the validity by executing it directly in your db
where do you connect to the database??
use mysql_connect(string hostname, string username, string password'); to connect to the database and then execute the query after selecting your database using mysql_select_db..
First you should remove the extra ; on $name="edit".$i;;
Then, how do you post the values? I see no <form> attributes in your code, hence it cannot be posted.
Also, everything is in a for loop. $newname=($_POST['text']); is never being set.
Maybe instead of this:
if (isset($_POST[$name2]))
try this:
if ($name2!="")

Categories