The majority of this code works just fine, the database get updated when I click on the button, but the last query (the UPDATE one) doesn't execute for some reason.
I tried turning on mysql log on phpmyadmin, but even there it's not executed.
It doesn't show me any error, and I really don't know what could be wrong.
$query = "SELECT username, coins FROM users WHERE userid='$userid' LIMIT 1";
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
$_SESSION['username'] = $user['username'];
$_SESSION['coins'] = $user['coins'];
$op = $user['username'];
$op = mysqli_real_escape_string($forumdb, $op);
$postcontent = $_POST['postcontent'];
$postcontent = mysqli_real_escape_string($forumdb, $postcontent);
$posttitle = $_POST['posttitle'];
$posttitle = mysqli_real_escape_string($forumdb, $posttitle);
$sectionid = $_GET['sectionid'];
$sectionid = mysqli_real_escape_string($forumdb, $sectionid);
$query = "INSERT INTO topic (section_id, name, replies, op, lastpost, lastuserid, views, sticked) values('$sectionid', '$posttitle', '0','$op', CURRENT_TIMESTAMP(),'$userid', '0', '0')";
$result = mysqli_query($forumdb, $query) or trigger_error("Query Failed! SQL: $query - Error: ".mysqli_error($forumdb), E_USER_ERROR);
$last_id = mysqli_insert_id($forumdb);
$query = "INSERT INTO posts (topic_id, content, user_id) values('$last_id', '$postcontent', '$userid')";
mysqli_query($forumdb, $query);
$query = "UPDATE section SET lastpost='$username', threads=threads+1, posts=posts+1 WHERE id='$sectionid'";
mysqli_query($forumdb, $query) or trigger_error("Query Failed! SQL: $query - Error: ".mysqli_error($forumdb), E_USER_ERROR);
You can use the following to solve your problem:
"UPDATE `section` SET `lastpost`='$username', `threads`=threads+1, `posts`=posts+1 WHERE `id`='$sectioni
It would have been helpful if you explained what "doesn't execute for some reason" means.
Either you get an error indicating that the SQL was invalid at runtime or the execution continued and no data was changed.
Without knowing what the error was, we can't advise what would have caused an error. If execution continued, but the record was not (obviously) updated, then it must be because the WHERE clause of the update statement did not match any rows. You could verify this by checking mysqli_affected_rows().
The queries you have run previously wil be in the mysql general log. You might want to
echo the SQL statement to the output and check that it is populated as you expect
Related
All I need is to produce a row. I've looked at all the samples and I cannot for the life of me get the right information. Hence help is required please.
Connection to DB in the usual way. Here is my code for the query.
$sql = "SELECT * FROM table WHERE `u_password` = $pword AND `user` = $uname LIMIT 1";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
I've got a count in there and it produces a result of 1.
The error I get is
'Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result'
Help would be appreciated.
The error
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result
Almost always means that the query failed for some reason, thus $result = mysqli_query returns FALSE rather than a mysql_result object so anything that then tries to use $result as an object will not work for obvious reasons.
The issue with your query is that text column data must be wrapped in quotes like this
$sql = "SELECT *
FROM table
WHERE `u_password` = '$pword' AND `user` = '$uname' LIMIT 1";
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
You should use parameterized queries to avoid this.
$sql = "SELECT *
FROM table
WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
// its also a good idea to check the staus of a prepare
// and show the error if it failed, at least while testing
if ( $stmt === FALSE ) {
echo mysqli_error($mdb);
exit;
}
$stmt->bind_param('ss', $pword, $uname );
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['seeking'];
You need to use prepared statements (in actuality you could get it to work by quoting your strings but prepared statements are much better). Like so:
$sql = "SELECT * FROM table WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
$stmt->bind_param("ss",$pword,$uname);
if ($stmt->execute()) {
$result = $stmt->get_result();
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
} else { /* something went wrong */ }
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
I am trying to delete a file or copy a row into a new table, depending on a $_GET.
The $_GET works fine, and I'm not including all the code, I know it isn't relevant.
The table copy works, but the select statement that gets called when the $_GET is a different value returns nothing, except when I copy the query directly into phpmyadmin.
Base code:
$pID = $_GET['pID'];
$con = mysqli_connect("...","...","...","...");
The following works:
$query = 'INSERT INTO `photos` (`id`, `photo1`, `photo2`, `demographic_id`)
SELECT `id`, `photo1`, `photo2`, `demographic_id`
FROM `photos_queue`
WHERE `photos_queue`.`demographic_id` = '.$pID;
mysqli_query($con, $query);
This does not:
$query = 'SELECT `photo1` FROM `photos_queue` WHERE `demographic_id` = '.$pID;
$result = mysqli_query($con, $query);
print($result);
unlink($result);
I've printed $query and the value of it is valid; I can copy it directly into phpmyadmin and it will work fine.
mysqli_query() doesn't return the table data, it just returns a resource that can be used to fetch it. You need to do:
$result = mysqli_query($con, $query) or die (mysqli_error($con));
$row = mysqli_fetch_assoc($result);
$filename = $row['photo1'];
print($filename);
unlink($filename);
($row = mysqli_fetch_array($result)
This should be placed after,
$result = mysqli_query($con, $query);
I'm trying to create a function for my forum that will increment my user's "Posts" attribute by 1. For whatever reason, the following PHP does not work.
function postCountIncrease($username) {
//get the connection variable
global $con;
//change to the users database (this function works correctly)
sqlconnect_users();
//get current post number (this is also working)
$getCurrentPosts = "SELECT Posts\n"
. "FROM users\n"
. "WHERE Username='".$username."'";
$query1 = mysqli_query($con, $getCurrentPosts) or die(mysqli_error($con));
$currentPosts = mysqli_fetch_array($query1);
//here is the problematic post. Assume that $username is a valid value, and that I've already done mysqli_real_escape_string() on it
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
$query2 = mysqli_query($con, $incrementPostsQuery) or die(mysqli_error($con));
//return the result
$result = mysqli_fetch_array($query2);
return $result;
}
I honestly don't see what I'm doing wrong, because the SQL works fine. If I use UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames' in the console, it works with no errors. Help is much appriciated. Also, here is the error it is throwing at me:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 WHERE Username='Lampitosgames''
You can not concatenate that way "toto ".$var+1, you have to surround with brackets "toto ".($var+1)
In your case, this is declaration of var $incrementPostsQuery which fails
Look at your errors, your syntax is off
$getCurrentPosts = "SELECT Posts
FROM users
WHERE Username='$username'";
The error is in the building of your query.
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
I'll suggest you some tips to create query like this:
"update table set field = value"; // you can write the value directly
"update table set field = ". $value; // easy
"update table set field = ". ($a+$b); // ...
"update table set field = {$value}"; // you can add a variable with curly braces
"update table set field = {$va[3]}"; // more compless way
"update table set field = {$a->b}"; // an object field
I am trying to get last autoincrement id from INSERT/UPDATE query, i am trying this way, but its not working, it just echo id=0 every time.
PHP
require_once('conn.php');
$temp = 'temp';
$query = "INSERT INTO temp (temp) VALUES('$temp')";
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn), E_USER_ERROR);
$id = mysqli_insert_id($conn);
echo 'id = '.$id;
Please see and suggest any possible way to do this.
Try changing the query to.
INSERT INTO `temp` (`temp`) VALUES('$temp')