What is the problem in my code ? every time it echo This image used as cover image , but delete query work properly.how can i fix it?
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if (isset($_GET['ximgid'])) {
$del=mysql_query("Delete FROM project_image WHERE ximgid='".$_GET['ximgid']."' And coverflag !='1'");
$delete=mysql_num_rows($del);
if($delete==1){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
}
?>
mysql_num_rowsonly works with selectstatement.
For delete statements you have to use mysql_affected_rows
Here the part of the documentation of mysql_affected_rows:
Retrieves the number of rows from a result set. This command is only
valid for statements like SELECT or SHOW that return an actual result
set. To retrieve the number of rows affected by a INSERT, UPDATE,
REPLACE or DELETE query, use mysql_affected_rows().
mysql_affected_rows() is the way to go
$delete=mysql_affected_rows($del);
if($delete>0){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!') </script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else if($delete==0){
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('mysql error')</script>";
}
I had to solve my problem in an alternative way which is given below:
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if(isset($_GET['ximgid'])){
$selQuery = "SELECT coverflag FROM project_image WHERE ximgid ='".trim($_GET['ximgid'])."' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$flagtResult=mysql_query($selQuery);
$flagRow=mysql_fetch_array($flagtResult);
mysql_free_result($flagRow);
$cover=$flagRow[0];
if($cover == 1){
echo "<script type='text/javascript'>alert('Used as cover picture')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
$sql = "DELETE FROM project_image WHERE ximgid = '".trim($_GET['ximgid'])."' AND coverflag != '1' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$result = mysql_query($sql) or die(mysql_error());
if($result > 0){
echo "<script type='text/javascript'>alert('Sucessfully Detele !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}
}
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
?>
Now I can get my proper output.. Thanks Everyone.
first of all it appears that you are escaping ximgid and coverflag with ' which would throw a syntax error in your sql if those were not varchar fields.
$del=mysql_query("Delete FROM project_image WHERE ximgid=".$_GET['ximgid']." And coverflag !=1;");
Second issue to address would be that you are taking a $_GET parameter and putting it directly into your SQL query which is just trouble looking to happen so I would suggest next changing it to:
$del=mysql_query("Delete FROM project_image WHERE ximgid=".mysql_real_escape_string($_GET['ximgid'])." And coverflag !=1;");
if you need extra help debugging your SQL you can always temporarily put a call to
echo mysql_error();
after your call to mysql_query in order to show the error message from the server.
Related
Hi i have an slight problem i'm trying top geht tow Results of My pdo query and Print Them but No such luck i've probably just Made a Stupid mistake i'm Not seeing The query seems to be finde so it does make a difference if the name is in the database (and it makes a difference if you put it in quotes) probably the variables are getting a null value or something...
$username="xxx";
$firstname="xxx";
$check=0;
if (isset($_GET['u'])){
$username=strip_tags(#$_GET['u']);
if (ctype_alnum($username)){
$check=$stmt=$link->prepare("SELECT * FROM
users WHERE username = ?");
$stmt->execute(array($username));
$check=$stmt->fetchAll();
if(count($check)==1){
$get=$stmt->fetch(PDO::FETCH_BOTH);
echo "$get";
$username =$get["username"];
$firstname = $get["first_name"];
}else{
echo "<h2> User does not exist!</h2>";
exit();
}
}
}
?>
<h2>Profilepage for: <?php echo "$username"; ?></h2>
<h2>First name: <?php echo "$firstname"; ?></h2
$stmt->fetchAll() is fetching all the results of the query. Once this is done, there are no more results available for $stmt->fetch() to fetch. You should get the data from the $check array.
if (count($check) == 1) {
$get = $check[0];
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Or you could just replace the fetchAll with fetch.
$stmt->execute(array($username));
$get = $stmt->fetch(PDO::FETCH_ASSOC);
if ($get) {
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Also, echo "$get" makes no sense. $get is an array, you can't echo it, you need to use print_r($get) or var_dump($get).
I've searched thoroughly and nothing seems to be working; I have this code here which posts into my database but the problem is I am trying to run a conditional which checks if a row exists using the mysqli_num_rows function, but it is not actually working. I have tried many different versions and other functions as well such as mysqli_fetch_row, but nothing seems to work. Here is my code:
if (!empty($_POST)) {
$db_conx="";
$name = $_POST['name'];
$module = $_POST['module'];
$secret = $_POST['secret'];
$uid1 = $dmt->user['uid'];
$queryA = "INSERT INTO table_a (uid1,name,module,secret) VALUES ('$uid1','$name','$module','$secret')";
$resultA = mysqli_query($db_conx,$queryA);
$queryB = "SELECT 1 FROM table_a WHERE name='$name' LIMIT 1";
$resultB = mysqli_query($db_conx,$queryB);
$resultC = mysqli_query($db_conx,$queryB);
$query = mysqli_query($db_conx,"SELECT * FROM table_a WHERE name='$name'");
if (empty($name)||empty($module)||empty($secret)) {
echo "Oops! Can't leave any field blank <br />";
exit();
} elseif(mysqli_num_rows($query) > 0){
echo "name already exists.";
exit();
} elseif ($db_conx->query($queryA) === TRUE) {
echo "New record created successfully.";
exit();
} else {
echo "Error: " . $queryA . "<br>" . $db_conx->error;
exit();
}
}
As you can see the query appears to run but indeed does not do what it's told.
The first line of code inside your IF is destroying the variable you are using to hold the database connection
if (!empty($_POST)) {
$db_conx=""; // get rid of this line
So basically nothing using the mysqli API will work.
ALSO:
Add these as the first 2 lines of a script you are trying to debug
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
as you are obviously not readng your php error log
I want to check if my table is empty I've tried this "which I think that is the solution"
$test_empty="SELECT *FROM objectif where 1 ";
if(empty($test_empty))
{
echo "I m here";
}
But it seems that it doesn't work.
Depending on how you are connecting to your database (for example, using mysqli):
$db = new mysqli("localhost","username","password","dbname");
$check = $db->query("SELECT COUNT(*) FROM objectif");
if ($check->num_rows == 0 || $check->fetch_field() == 0){
echo "table is empty";
}else{
echo "table is not empty";
}
Currently, your code isn't actually connecting to the database or querying the table - you are essentially just checking if the variable $query is empty (which it never will be, as it contains a string!
Running a query to fetch the number of records and checking that as per the code above is one way to do this.
Use this
$mysqli = new mysqli("localhost","root","","db");
if ($result = $mysqli->query("SELECT * FROM `table` LIMIT 1"))
{
if ($obj = $result->fetch_object())
{
echo "NOT EMPTY";
}
else
{
echo "empty";
}
$result->close();
}
$mysqli->close();
Please try below code :
$test_empty="SELECT * FROM objectif";
$query = mysql_query($test_empty);
if(mysql_affected_rows() > 0)
{
echo "It is Empty";
}
I'm trying to delete records from my database using a form. Can't get this to work.
Any ideas?
include 'newsconnect.php';
$Id = $_POST['Id'];
if (empty($Id) === true {
echo 'please input an Post ID.';
} else {
if(!$_POST['Submit']) {
header('Location: http://www.hidensecrets.yourwebsolution.net/forum.php');
} else {
mysql_query("DELETE * FROM forum WHERE id = '$Id'") or die(mysql_error());
header('Location: http://www.hidensecrets.yourwebsolution.net/forum.php') ;
echo "Deleted!";
}
}
I seem to land on this page which displays no errors.
Any help is really appreciated.
Missing a closing bracket:
include 'newsconnect.php';
$Id = $_POST['Id'];
if (empty($Id)) {
//-^
echo 'please input an Post ID.';
} else {
if (!$_POST['Submit']) {
header('Location: http://www.hidensecrets.yourwebsolution.net/forum.php');
} else {
mysql_query("DELETE FROM forum WHERE id = '$Id'") or die(mysql_error());
header('Location: http://www.hidensecrets.yourwebsolution.net/forum.php');
echo "Deleted!";
}
}
Not sure which IDE you're using but most of them would show this error. You're also open to sql injection. Find out more.
What sort of issue are you facing? You're missing a closing parenthesis for if (empty($Id) === true in case the you're getting syntax error
I think that you must omit the asterisk in your delete query ! Try it and tell me the result :)
your code must use this query :
mysql_query("DELETE FROM forum WHERE id = '$Id'") or die(mysql_error());
instead of this one :
mysql_query("DELETE * FROM forum WHERE id = '$Id'") or die(mysql_error());
Hope this it will be the solution :)
I have a search field on my site that searches the database I use.
When I click on the search field and enter no text the search returns all results.
How can I have it so no results are returned if nothing is entered?
Is there any javascript that can help me?
Thanks!
James
<?php
$conn = mysql_connect("---", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("weezycouk_641290_db1")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '%".$search."%' AND lastname LIKE '%".$searchterm."%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if(document.getElementById('search').value == '')
return false;
if(document.getElementById('searchterm').value == '')
return false;
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br>';
echo '<br>';
echo '<div class="data1">';
echo $row["name"];
echo '</div>';
echo '<br>';
echo '<div class="data2">';
echo $row["lastname"];
echo '</div>';
echo '<br>';
echo '<div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
Stop right there! SQL injection!
Your code has multiple SQL injection vulnerabilities. Fix them immediately!
Fixed? Let's go on.
Before deciding to perform the search, check if the search term is the empty string. If yes, do not perform the search. For example:
$search = // whatever the user typed; it's a good idea to trim() it
if(empty($search)) {
// return no results
}
else {
// do whatever you normally do
}
You could also perhaps change the search function (more likely, the search SQL query) to return no results if there's nothing to search for, which would basically let you move the above if "deeper inside" your code. IMHO it's best if the if stays here though, so I don't endorse this approach.
Taking care of details with Javascript: If your search is based on a form submission, it might be a good idea to prevent the submission entirely (with Javascript) if the search field is empty as a courtesy to the user. However, you should do this in addition to using the PHP check and not instead of it.
For an example in code, we 'd need to see your HTML.
For very basic control you can do something like that.
if(document.getElementById('searchField').value == '')
return false;
Either you can deny submitting the search form as long as nothing is filled in the search field using Javascript or you block the search in the according php file.
php:
if(empty($_GET['search'])){ // or whatever your field's name is
echo 'no results';
}else{
performSearch(); // do what you're doing right now
}
javascript using jQuery (if you use it):
$('#searchform').submit(function(){ // replace 'searchform' your form's id
return $('#search').val() != ''; // and 'search' with your search field's id
});
I wouldn't do this using JavaScript (as this can be turned off by the user).
I would do it using your server side language when you process the query.
e.g. in PHP something like this would work:
<?php
//processes
if (trim($_GET['search'])=='') {
//dont query anything
} else {
// do your query
}
//output
if (trim($_GET['search'])=='') {
?>
<p>Sorry, your search has returned no results.</p>
<?php
} else {
// output results
}
?>