MySQL/PHP update query not executing - php

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!="")

Related

Why aren't the values from my form inserting into the database?

I have the following form:
<form id ="classadderform" action="formsubmit.php" method="POST">
<input type ="checkbox" name="note" value = "Note1"></input>
<input type="submit" value="Click Me" style="width:300px;">
</form>
Upon submit, the code redirects to formsubmit.php. Part of the code there is the following:
$db = new mysqli("sql...byethost8.com", "b8_163//....(database info));
$id = $_SESSION['id'];
.......
if(isset($_POST['note'])){
if($id){
$db->query("UPDATE answers SET WordLevel = 'Difficult' WHERE user_id=$id"); //<<<UPDATES SUCCESSFULLY
$notevalue=$_POST['note'];
$db->query("INSERT INTO answers (user_id, ValueColumn) VALUES ($id,'$notevalue')"); //<<<<<DOESN'T UPDATE
The WordLevel column updates successfully, but the value of the input named note does not insert into the column titled ValueColumn. This was working in my code a few days ago but it somehow stopped working. I tried different iterations of single quotes around $id and $notevalue but nothing seems to resolve the issue.
Any help would be much appreciated!
Execute and clear before the second query.
O you can try concating queries together using semicolon
$db->query("FIRST QUERY ; SECOND QUERY");
If you dont need the output of first query.
PDO multiple query
mysqli multiple query
might also help real_query

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.

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'];

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

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.

MySQLI string Won't update Info

I can't find out why when I click my submit button it doesn't process the data. I currently have a query as such.
$link = mysqli_connect("$server", "$user", "$pass", "webdb");
$page = mysqli_real_escape_string($link, (string) $_POST['page']);
$content = mysqli_real_escape_string($link, (string) $_POST['content']);
$query = "UPDATE `pages` SET `content`='$content' WHERE `name`='$page'";
mysqli_query($link, $query);
mysqli_close($link);
header("location: index.php");
?>
To connect to this query I have my form that submits the data.
<form action="update_content.php" method="post">
<textarea name="content" cols="60" rows="10"></textarea>
<input type="hidden" name="page" value="Index" />
<br /><input type="submit" value="Update" />
</form>
Everything looks to be correct from where I stand. I've been racking my brain and looking all over the web for hours now and I cannot find a solution here.
Step 1 :
Print the query variable, so that you can know the query is constructed well.
(Comment the redirection so that you can see the query output)
Step 2:
If the values passed in the query aren't correct or empty, fix this by printing the
passed params (you can print $_REQUEST - Which will show all the values posted)
Step 3
if all these are correct and if the query is not executed correctly, then check your
database connection.
You can print out the connection variable $link to see if a connection is made successfully.
These these steps will help you sort out the issue.
Let me know if these steps doesn't help you.
The actual answer was when the redirect was disabled I was able to see that the connection was failing which was something I wasn't able to see until the redirect was disabled in order to see the echo $query string. Lesson Learned: Check to ensure all variables are correct. :)

Categories