I would like to update information that is already in the database, but using an array. I get 'successfully update' message white the data in the database is not updated.
the following is the function I use to do the insertion:
function update_knowledge_modules($update_data,$value)
{
$update = array();
array_walk($update_data,'array_clean');
foreach($update_data as $field=>$data)
{
$update[] = '.$field. = \''.$data.'\'';
}
$query = "UPDATE knowledge_modules SET".implode(', ',$update)."WHERE curr_code =$value";
mysql_query($query)
or die(mysql_error);
}
<?php
if(isset($_GET['success']) == true && empty($_GET['success'])==true)
{
echo 'Changed successfully';
}
else
{
if(empty($_POST)== false && empty($errors)== true )
{
$update_module = array(
'KM_Number'=>$_POST['KM_Number'],
'KM_Title'=>$_POST['KM_Title'],
'NQF_Level'=>$_POST['NQF_Level'],
'Credits'=>$_POST['Credits']
);
update_knowledge_modules($update_module,$_SESSION['Curr_Code']);
header('Location:edit_km_details.php?success');
exit();
}
else if(empty($errors)== false)
{
echo output($errors);
}
?>
<form action="edit_km_details.php" method="POST">
Well, first of all, you are outputting the "changed successfully" message solely based on $_GET['success'] being truthy. It has nothing to do with whether you had success or failure in your update_knowledge_modules function call at all, which seems odd.
Second of all, I don't see anywhere where you are actually making a database connection.
Third, your query is undoubtedly being formed improperly. Look at this:
$update[] = '.$field. = \''.$data.'\'';
you are going to get a literal $field and backslashes in your query string. Try this:
$update[] = $field . " = '" . $data . "'";
Also where you put your imploded array in the final query, you don't have spaces after SET and before WHERE.
Anytime you are having problems with a query, just var_dump it and run it on the database directly to see why it isn't working and look at your errors, including mysql errors.
Finally, you should not be using the mysql_* family of functions. They are deprecated.
Try: $update[] = $field . " = '" . $data . "'";
Output:
Array
(
[0] => KM_Number = 'blah'
)
Related
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
I’m trying to write a PHP script with MySQLi to query a database.
I’d like it if the user-input could be checked against the database and then return a result from the column ‘conjugation’ if the string in the column ‘root’ of the table ‘normal_verbs’ is in the input.
So if the user input is something like "foobar", and the root-column has "foo", I'd like it to see 'foo' in 'foobar' and return that value of 'conjugation' in that row.
I can’t seem to get the query to work like I want it to. The one I'm using below is basically just a placeholder. I don't entirely understand why it doesn't work.
What I’m trying, is this :
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('localhost','user','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$m= db_query("SELECT `conjugation` from normal_verbs where `root` in (" . $y . ")");
if($m === false) {
// Handle failure - log the error, notify administrator, etc.
} else {
// Fetch all the rows in an array
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
print_r ($rows);
It’s not giving me any errors, so I think it’s connecting to the database.
EDIT2: I was wrong. I was missing something obvious due to misunderstanding MySQLi and have edited the code accordingly. So the above code does work in that it connects to the database and returns a result, but I'm still stumped on a viable SQL statement to do what I want it to do.
Please try this:
SELECT 'conjugation' FROM 'normal_verbs' WHERE " . $y . " LIKE CONCAT('%',root,'%')
It selects all rows where root contains $y anywhere.
In addition, your code is vulnerable to SQL injections. Please look here for more information.
Try this SQL Query Like this
SELECT `conjugation` from normal_verbs where `root` like '%$y%'
So, I have some code. I know that mysql_num_rows is deprecated, but since I've already used it I don't want to switch everything to mysqli_. Anyway it was working on my local server and returning 1 or more results based on the entry. This is a PHP login script that I'm trying to get to work. When I uploaded the script to my hostgator server it didn't work. I also checked the PHP version and it mysql_num_rows() shouldn't be deprecated in version 5.4.xxx.
When I try doing a test query of just SELECT * FROM customers it returns one row, but it's not returning anything when I search for where the user and password equal the posted variables. It's frustrating me, and I could use a second set of eyes to look at this.
<?php
include('mysql_connect.php');
if(isset($_POST['submit'])) {
if(isset($_POST['cususername']) AND isset($_POST['cuspassword'])) {
$username = $_POST['cususername'];
$password = md5($_POST['cuspassword']);
$query = "SELECT * FROM customers WHERE username = '" . $username . "' AND
password = '" . $password . "'";
$returned_user = mysql_query($query);
$number_of_users = mysql_num_rows($returned_user);
if($number_of_users > 0){
echo "It got this far!";
$customer_array = mysql_fetch_array($returned_user);
$_SESSION['user_logged'] = 1;
$_SESSION['id'] = $customer_array['customer_id'];
$_SESSION['user_name'] = $customer_array['username'];
}
}
}
?>
<?php
if(isset($_REQUEST['loggoff'])) {
unset($_SESSION['user_logged']);
unset($logged_status);
}
if(isset($_SESSION['user_logged'])) {
$logged_status = $_SESSION['user_logged'];
}
if(isset($logged_status)) {
if($logged_status == 1) {
echo "You are logged in as " . $_SESSION['user_name'] . ", Click here to <a href='" . $_SERVER['PHP_SELF'] . "?loggoff=1'>Log off</a>" . "<br>";
}
}
else {?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="customerlogin">
<input type="text" name="cususername" id="cususername" />
<input type="password" name="cuspassword" id="cuspassword" />
<br />
<input type="submit" name="submit" value="Login" />
</form>
<?php}?>
You should check if you have an mysql_error in your query.
Btw. you should mysql_real_escape your POST data before use in a mysql_query
If you would use columns names as array index you must use mysql_fetch_assoc() instead of mysql_fetch_array();
Try this Code:
<?php
include('mysql_connect.php');
if( isset( $_POST['submit'] ) )
{
if( isset( $_POST['cususername'] ) AND
isset( $_POST['cuspassword'] ) )
{
// Prevent mysql injection
$username = mysql_real_escape_string( $_POST['cususername'] );
$password = md5( $_POST['cuspassword'] );
$query = "SELECT * FROM `customers` WHERE `username` = '" . $username . "' AND `password` = '". $password ."'";
$result = mysql_query( $query );
// Check if error
if( mysql_errno() !== NULL )
{
exit( "An mysql_error has occured: \r\n".
"Err-No: " . mysql_errno() . "\r\n".
"Err-Msg: " . mysql_error()
);
}
// Everything is okay .. Go on
$iRows = mysql_num_rows( $result );
// Check if only one user was found
if( $iRows === 1 )
{
echo "It got this far!";
$customer = mysql_fetch_assoc( $result );
// Use boolean value instead of numbers
$_SESSION['user_logged'] = true;
$_SESSION['id'] = $customer['customer_id'];
$_SESSION['user_name'] = $customer['username'];
}
}
}
I hope I could help you.
If this code wouldn't work try to output the generated sql statment and try it self in your SQL Admintool (e.g. phpMyAdmin).
Sorry for my bad english :/
One Suggestion. Rather Than 'AND'. Use '&&'. Some Codes do not execute using AND in if conditon. Just a suggestion.
if(isset($_POST['cususername']) && isset($_POST['cuspassword']))
Ok guys, and for all those with a similar problem searching. Here is my answer. The password field wasn't matching up with the inputted $_POST. So, I got online and looked up an answer. Come to find out the password was varchar(25), which was cutting off the md5 hash. This was what was causing MySQL_NUM_ROWS() to return 0. Don't worry I will add MySQL injection prevention to my script as suggested by few of you, including Chris Wittor. Also, I know that md5 is an outdated way of encypting the information, but it's better than plain text.
This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
first time here. I'm struggling to get this PHP function to work, and after 5 hours it's driving me insane.
I have this function:
// DOES THE USER HAVE ACCESS?
function access_la_page($id) {
include('DB_db.php');
/// GENERATE SQL
$sql = "SELECT parent FROM la_pages WHERE id = $id";
// PREPARE THE STATEMENT
$result = mysqli_query($conn, $sql);
if($result === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
echo "FAIL" . $conn->error; exit();
}
$row = mysqli_fetch_array($result);
// CHECK PERMISSIONS DATABASE TO SEE IF USER HAS ACCSS HIGHER UP THE CHAIN
$sql2 = "SELECT * FROM la_pages_permissions WHERE la_page_id = $id AND user_id = " . $_SESSION['user_id'];
$result2 = mysqli_query($conn, $sql2);
if($result2 === false) {
trigger_error('Wrong SQL: ' . $sql2 . ' Error: ' . $conn->error, E_USER_ERROR);
echo "FAIL" . $conn->error; exit();
}
if(mysqli_num_rows($result2) > 0){
$value = TRUE;
return $value;
}elseif($row['parent']!==$id&&$row['parent']&&!isset($value)) {
access_la_page($row['parent']); // CHECK DB RECURSIVELY TO SEE IF USE HAS PERMISSION HIGHER UP THE CHAIN
}
}
I then call this function:
if(access_la_page($_SESSION['la_page_id'])==TRUE){
echo "Success";
}else{
echo "Fail";
}
Now... If the function hits TRUE on the first instance it will in fact return TRUE to my page, success! But if it loops it does not return TRUE. It returns nothing.
But, when I echo from the statement I can see that the function is performing as it should, and when I echo $value, it shows TRUE and the function ceases - which is what should happen. But the function does not return TRUE.
Does that make sense, is this not working because I'm looping through the function?
EDIT - Excuse my ignorance. I had TRUE in quotes, I've modified that now but it doesn't work still
Your final If statement will return 'TRUE' if it passes, but won't return anything if it does not.
Can you confirm this, as at the moment that function is returning either 'TRUE' or null.
This might be the cause.
Try a return on the last clause, if the recursive check is meant to help decide, then it should return something:
if(mysqli_num_rows($result2) > 0){
$value = "TRUE";
return $value;
}elseif($row['parent']!==$id&&$row['parent']&&!isset($value)) {
return access_la_page($row['parent']); // CHECK DB RECURSIVELY TO SEE IF USE HAS PERMISSION HIGHER UP THE CHAIN
}
Change
$value = "TRUE";
to
$value = TRUE;
Andy Gee's answer it correct,
plus you can shorten your if statement condition to
if(!($result)){
code here
}
I am trying to pass an array of data to a Update query, to update customer records. However for some reason the ?success page is showing saying my details have been updated, however they aren't. If I debug and echo
echo implode(', ', $update);
die();
I get the result
mem_first_name = 'Josh', mem_last_name = 'smith', mem_email = 'j.smith#gmail.com', allow_email = '0'
Which looks fine to me. This is my update_user function
function update_user($mem_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id` = '$mem_id'") or die(mysql_error());
}
And my $update_data array
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
$message = 'Your details have been updated';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$update_data = array(
'mem_first_name' => $_POST['mem_first_name'],
'mem_last_name' => $_POST['mem_last_name'],
'mem_email' => $_POST['mem_email'],
'allow_email' => ($_POST['allow_email']) ? 1 : 0
);
update_user($session_member_id, $update_data);
header('Location: settings.php?success');
exit();
} else if (empty($errors) === false) {
$message = output_errors($errors);
}
}
So I have worked out I am losing my backticks after I implode, thus the column names don't have back ticks
This is some sort of typo (and thus not a real question of course).
You are adding backticks to your fields
$update[] = '`' . $field . '`
^ here
But they are absent in the debug out.
So, you are either run or post wrong code, which makes whole question pointless.
check connection with db, and table field name spells., i think no problem in this code.