I am trying to delete a record in a MYSQL database when I need to select two simultaneous columns with the WHERE clause:
$result3 = mysqli_query($con, " DELETE FROM Waiting WHERE ToUser='$ToEmail' AND ImageID='$ToEmailDB' ");
if ($result3==false) {
echo "No images waiting for " . $ToEmail . " for image " . $ToEmailDB;
}
else {
echo "Image and record deleted for " . $ToEmail . " for image " . $ToFileName . ".jpg and record " . $GuessImageID;
}
When I execute this statement $result3 returns true but the entry is not deleted. What do I need to change in my formatting? The strings echo back correct data entered in the table.
Shouldn't it be,
"DELETE from Waiting WHERE ToUser = '" . $ToEmail . "' AND ImageID = '" . $ToEmailDB . "'"
$result3 = mysqli_query($con, "DELETE FROM Waiting WHERE ToUser='".$ToEmail."' AND ImageID='".$ToEmailDB."' ");
The query will return true if the SQL query executes successfully, even when the DELETE didn't remove any rows in the DB.
http://php.net/manual/en/mysqli.affected-rows.php
To answer your question, you need to find the number of rows affected
$result3 = mysqli_query($con, " DELETE FROM Waiting WHERE ToUser='$ToEmail' AND ImageID='$ToEmailDB' ");
if (!$result3) {
echo "A database error occurred";
}
else if (mysqli_affected_rows($con) == 0) {
echo "No images waiting for " . $ToEmail . " for image " . $ToEmailDB;
}
else {
echo "Image and record deleted for " . $ToEmail . " for image " . $ToFileName . ".jpg and record " . $GuessImageID;
}
Your query always returns TRUE if its executed successfuly. Only on query failures it returns FALSE As per the PHP documentation:
mysqli_query() Returns FALSE on failure. For successful SELECT, SHOW,
DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
For other successful queries mysqli_query() will return TRUE.
From Moby04's Comment
If you want to check if something was actually deleted use mysqli_affected_rows() function.
Related
I need to send the values of username, password, mail, first name and last name into two different tables in my database. I have made that possible with this code, and i get the values correct. I have one problem tho. When the user-info goes into "users" table, it auto-generates one userId. That same userId i need to use and put into the other table "usermeta" to connect the information to the correct user. What happens now is that i get a userId in the users table, but in the usermeta table the userId is = 0 on all new users. Can anyone help me?
if (isset($_POST['username']) and isset ($_POST['password'])) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($mysqli->real_escape_string($_POST['password']));
$email = $mysqli->real_escape_string($_POST['mail']);
$fname = $mysqli->real_escape_string($_POST['fname']);
$lname = $mysqli->real_escape_string($_POST['lname']);
$query = <<<END
INSERT INTO users(username,pass,email,admin)
VALUES('{$username}','{$password}','{$email}','{$_POST['admin']}')
END;
$q = <<<END
INSERT INTO usermeta(first_name,last_name)
VALUES('{$fname}','{$lname}')
END;
if ($mysqli->query($query) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
}
if ( $mysqli->query($q) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
header('Location:home.php');
}
}
I got a form further down in the code that the info comes from that's going to the database, but it's the php-code that makes the error i assume to i exclude that code.
Thanks!
EDIT:
I've tried to implement your different comments. Thanks alot for the answers!
If i try to get the latest id inbetween the $query and $q, the output is 0. If i use the command:
if ($mysqli->query($query) === TRUE) {
$last_id = $mysqli->insert_id;
echo $last_id;
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
I get the correct id. But how can i use that variable to the new $q? It seems that the function breaks after the if is done.
Thanks! :)
You can use LAST_INSERT_ID() to retrieve the value of the auto-increment id that was created in your last insert. (Docs here)
So try:
$q = <<<END
INSERT INTO usermeta(first_name,last_name, userId)
VALUES('{$fname}','{$lname}', LAST_INSERT_ID();)
END;
Okey i managed to get it done. Thanks guys for the help!
The working code looks like this:
$query = <<<END
INSERT INTO users(username,pass,email,admin)
VALUES('{$username}','{$password}','{$email}','{$_POST['admin']}')
END;
if ($mysqli->query($query) === TRUE) {
$last_id = $mysqli->insert_id;
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
$q = <<<END
INSERT INTO usermeta(first_name,last_name, user_id)
VALUES('{$fname}','{$lname}','{$last_id}')
END;
if ($mysqli->query($q) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
}
Is there something wrong with my function here? I've created a simple task manager with a blog page as well. This is the same function I use to update Tasks in the task table, just modified to update the Blog table instead.
function update_blog($blogpost) {
global $db;
$sql = "UPDATE Blog SET ";
$sql .= "blog_date='" . db_escape($db, $blogpost['blog_date']) . "', ";
$sql .= "blog_content='" . db_escape($db,
$blogpost['blog_content']) . "' ";
$sql .= "WHERE id='" . db_escape($db, $blogpost['id']) . "' ";
$sql .= "LIMIT 1";
$result = mysqli_query($db, $sql);
if($result) {
return true;
} else {
// UPDATE failed
echo mysqli_error($db);
db_disconnect($db);
exit;
}
}
From edit.php, the user is redirected to blog.php upon submitting their blog post edits. However, the edits are not seen and the table itself is not updated. Am I missing something simple here?
It might have something to do with a record with db_escape($db, $blogpost['id']) not being present in the database (if the query is not failing). I would recommend executing a simple SELECT to see how many rows exist, e.g.:
SELECT *
FROM Blog
WHERE id = <value of db_escape($db, $blogpost['id'])>;
If you don't get any rows, that probably means there is no record present and hence, no update. You might have to pass different value in that case, depending on what you have in the form.
I am relatively new with using postgress, so I am trying to get results without using the PDO statements.
My code is as follows, now I successfully made a connection with the database, on execution my webpage has no results. On furthur inspection I noted that the while loop does not execute I know it is not a logical error with my query statement because I ran the same query on the database and it returned values.
I think the problem is in the while loop, but I cannot understand. This query on the database returned 43 results.
$query = "SELECT * FROM property WHERE latitude BETWEEN " .$lat1 ." AND " .$lat2 ." AND longitude BETWEEN " .$lng1 ." AND " .$lng2;
$result = pg_query($db, $query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
pg_result_seek($result,0);
while($myrow = pg_fetch_assoc($result)) {
echo "reached";
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['p_id'], htmlspecialchars($myrow['type']), htmlspecialchars($myrow['latitude']), htmlspecialchars($myrow['longitude']));
printf ("<br>");
Again to re-iterate, the results array is not empty because it does not throw an error message, I think there is an issue solely with the while statement.
Try adding qoutes(')
So:
$query = "SELECT * FROM property WHERE latitude BETWEEN '" .$lat1 ."' AND '" .$lat2 ."' AND longitude BETWEEN '" .$lng1 ."' AND '" .$lng2 . "'";
Let us know if it helped
I was wondering how to fetch data of a person from a table. I found the query to LIMIT data fetch from table. Here is what I got so far:
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
It returns data when LIMIT is available but if the LIMIT exceed the entire data returns null. So how can I know if ROW is available or not in table?
use mysql Count
SELECT count(username) FROM users WHERE username ='xyz'
And your $last_limt is not grater than total count-1
You have to check number of rows of the result from that query before proceeding
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
$rowcount=mysql_num_rows($result);
if($rowcount > 0)
{
//next operations
}
else
{
//No more data
}
Here is the answer to moving some data from one table to another it may not be the best, but it does work.
$result = mysqli_query($con,"SELECT * FROM Teacher_staff");
while($row = mysqli_fetch_array($result))
{
// you don't need this step but it checks the select data portion
echo $row['First'] . " " . $row['Last'] . " " . $row['Id'];
// assign your variables, might not need this step as well
$First = $row['First'];
$Last = $row['Last'];
$id = $row['Id'];
// takes the information from the first mysqli and inserts it into the second table.
$sql="INSERT INTO teachers (First, Last, Id)
VALUES
(
'".addslashes($First)."',
'".addslashes($Last)."',
'".addslashes($Depart)."',
'".addslashes($id)."'
)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
// confirms that each record is added to the table.
echo "1 record added";
}
echo "<br>";
mysqli_close($con);
echo "done";
Any way thanks for the help.... oh and I fixed it so that " ' " doesn't give an error.
Try this query.
$result = mysqli_query($con, "INSERT INTO Teachers (First, Last, Depart) SELECT First, Last, Depart FROM Teacher_staff");
That's literally all you should have to run.
If you have access to your database outside of PHP (phpMyAdmin or command line), I'd recommend running that query from there.