I am using PHP 7 and the latest mysql on ubuntu 16.10. This is the current code I have
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$sql = "DELETE FROM databasetable WHERE columnA LIKE '%Test7%'" ;
mysql_select_db('jdbdev');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
Should change to below query
DELETE FROM databasetable WHERE columnA like '%Test7%'
There is difference between = and like operator
It's not very clear for me what you are trying to accomplish using this:
WHERE columnA = '%Test7%'" ;
Is the percent sign a literal that should match just like that? As you probably know, percentage sign is a wildcard in mysql and it should be use with LIKE rather than equal.
In this case, your condition will be:
WHERE columnA LIKE '%Test7%'`
If you want to use wildcard % then you have to use LIKE instead of =, so change your sql to:
"DELETE FROM databasetable WHERE columnA LIKE '%Test7%'"
Also, mysql functions are vulnerable to sql injection, you should use mysqli or even better PDO to manage your database.
Try:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$db_name = 'jdbdev';
$conn = mysqli($dbhost, $dbuser, $dbpass, $db_name);
try{
if($conn->connect_error){
echo 'Could not establish connection to database because '.$conn->connect_error;
}
}catch(Exception $ex){
echo $ex->getMessage();
exit;
}
$sql = "DELETE FROM databasetable WHERE databasetable.columnA LIKE '%Test7%'";
$retval = $conn->query($sql);
if($retval === FALSE) {
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
Sometimes, you have to reference the database table in front of the column
$sql = "DELETE FROM databasetable WHERE columnA = '%Test7%'" ;
should be columnA like '%test7%'
$sql = "DELETE FROM databasetable WHERE columnA like '%test7%'
Like and = both are different.
Assuming you're trying to delete all the rows where columnA contains the test "Test7", you need to use the like operator, not the = operator:
DELETE FROM databasetable WHERE columnA LIKE '%Test7%'
-- Here --------------------------------^
Related
When I execute the statement in phpmyadmin, it works properly, but when I copy and paste the exact same query into this php file, it doesn't work.
PHP Code:
if($_GET['vote'] == 1) {
echo "if statement ran";
$sql = "UPDATE raids SET attendees = attendees +1 WHERE dateposted = '2017-08-19 16:15:46'";
mysql_query($sql, $link);
}
My link variable does work and the 'if' statement executes. Other SQL statements haven't given me trouble.
Why isn't the php code incrementing 'attendees' when used in the PHP code?
As Milan Chheda said, MySQL is deprecated and is no longer secure. Use PDO or at least MySQLi instead.
MySQLi implementation for your code:
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
if(isset($_GET['vote']) && $_GET['vote'] !== NULL) {
$vote = $_GET['vote'];
if($vote == "1") {
echo "Vote is 1, updating the database";
$sql = mysqli_query($connection, "UPDATE raids SET attendees = attendees + '1' WHERE dateposted = '2017-08-19 16:15:46'");
}
}
I hope this helped you. Good luck!
I wrote this simple code to delete a blog from the sql table. But its giving an error
Could not delete data: Unknown column '$qid' in 'where clause'
Cant understand why. $qid is the variable while just qid is the column name and its giving me this error.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('trial1');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
function check_login(){
return 12;
}
$return_array = array();
if( check_login()!=NULL){
$qid =1;
$sql='DELETE FROM blog_post WHERE qid = $qid';
$retval = mysql_query($sql, $conn);
if (!$retval){
die('Could not delete data: ' . mysql_error());
$return_array["success"] = 0; //If deletion unsuccessful
echo json_encode($return_array);
}
else{
$return_array["success"]=1; //If deletion successful
echo json_encode($return_array);
}
}
?>
Variables will not be parsed under single quotes. Enclose the SQL query under double quotes ".
$sql="DELETE FROM `blog_post` WHERE `qid` = $qid"; //<-- Like this.
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !
You should wrap your input in the sql with single quotes :
$sql="DELETE FROM `blog_post` WHERE `qid` = '$qid'";
Very first you need to make sure you have a column name qid in table.
Then try:
$sql='DELETE FROM blog_post WHERE qid ='.$qid;
I'm trying to update a record in my database using the code below. I'm trying to change the product name but I am getting the following error:
Could not update data: Unknown column 'Earrings' in 'field list'
Code:
<?php
if(isset($_POST['update']))
{
$dbhost = 'databasehost';
$dbuser = 'username';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$ProductsID = $_POST['ProductsID'];
$ProductsName = $_POST['ProductsName'];
$sql = "UPDATE Products ".
"SET ProductsName = $ProductsName ".
"WHERE ProductsID = $ProductsID" ;
mysql_select_db('databasename');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
The query should be
$sql = "UPDATE Products ".
"SET ProductsName = '$ProductsName' ".
"WHERE ProductsID = $ProductsID" ;
You forgot to wrap $ProductName with quotations. Don't forget to do so when dealing with string values.
You want something like this:
ProductsName = '$ProductsName'
Also, be sure to escape that input, else you'll be subjected to SQL injections.
Your are trying to set the ProductsName to an existing column, add quotes to let sql interpret a value:
$sql = "UPDATE Products ".
"SET ProductsName = '$ProductsName' ".
"WHERE ProductsID = $ProductsID" ;
You are not sanitizing your data, so there is a good chance that your query could break depending on the value submitted, not to mention it leaves your database wide open for an attacker to manipulate via SQL Injection.
Please do not use mysql_ functions, as they are depricated. You should be using prepared statements, please see PDO and mysqli.
As for your answer, you need to put 'quotes' around the $variable
Got a strange error saying that I'm not connected to a database while running a mysqli_num_rows query. Here is the code:
<?php include("php/functions.php"); ?>
<?php
if(isset($_GET['verification']) && !empty($_GET['verification'])){
// Verify data
$hash = mysqli_real_escape_string($con, $_GET['verification']); // Set hash variable
$search_sql = "SELECT 'hash', active FROM members WHERE hash='".$verification."' AND active='0'";
$search_res = mysqli_query($con, $search_sql);
$match = mysqli_num_rows($search_res);
Any ideas why this isn't working?
I have changed several things in your code, please review.
If you are using the mysqli class then anything after your class instatiation should look something like:
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$con->exampleClassFunction()
using the object operator ->.
To get the num_rows your object operator would be after the query variable, like so:
$search_res = $con->mysqli_query($con, $search_sql);
$match = $search_res->mysqli_num_rows($search_res);
I also added the backticks to all applicable column names in your query:
SELECT `hash`, `active` FROM members WHERE `hash`='".$verification."' AND `active`='0'
Here is an example with your code:
//include("php/functions.php");
$DB_NAME = 'DATABASE_NAME';
$DB_HOST = 'DATABASE_HOST';
$DB_USER = 'DATABASE_USER';
$DB_PASS = 'DATABASE_PASSWORD';
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
// Added a connection error check before continuing
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_GET['verification']) && !empty($_GET['verification'])){
$hash = $con->mysqli_real_escape_string($con, $_GET['verification']);
// Use back ticks on query column names,
// use single quotes for comparative operations
$search_sql = "SELECT `hash`, `active` FROM members WHERE `hash` = '".$verification."' AND `active` = '0'";
$search_res = $con->mysqli_query($con, $search_sql);
$match = $search_res->mysqli_num_rows($search_res);
}
<?php include('functions.php'); ?>
Also, make sure you have your closing ?> tag in the correct place.
just try to make it include("functions.php")..
I think thats your problem
<?php
include("functions.php"); //includes databse connection
$search_sql = "SELECT hash, active FROM members WHERE hash='".$verification."' AND active='0'";
$search_res = mysqli_query($con, $search_sql);
$match = mysqli_num_rows($search_res);
?>
include("functions"); or include("functions.php"); ??? You forgot .php
You forget to add file extension.
<?php include("functions.php"); ?>
also put `
around hash as its reserved word by MySQL.
please try the below code:
<?php
include("functions.php"); //includes databse connection php file
$search_sql = "SELECT hash, active FROM members WHERE hash='".$verification."' AND active='0'";
$search_res = mysqli_query($con, $search_sql);
$match = mysqli_num_rows($search_res);
?>
include should have a .php file as parameter. please check it.
I have databases of users and each has tables. I want to loop through each user and find the number of rows of a particular table common to each. So i connect to the first DB(usersDB) and pick the names of other DB's from a table(userinfo) row(user_name). I then connect to each DB using the names obtained in userinfo and try to find the number of rows they each have on a particular table(products) common to them. I tried this but shows the same number of rows for all of them. Any help??
<?php
//db parameters
$dbhost = "localhost";
$dbname = "usersDB";
$dbuser = "root";
$dbpass = "";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
//select main db
$query = "SELECT user_name FROM userinfo";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_BOTH))
{
$dbName =$row['user_name'];
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
// do a query for each db
$query = mysql_query('SELECT * FROM `products`');
$num_rows = mysql_num_rows($query);
echo $dbName." has".$num_rows."products"."<br/>";
}
?>
I think problem is in following line
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
I think this line will be
mysql_select_db("dbprefix_".$dbName) or die("MySQL Error: " . mysql_error());
this may not be your issue but I noticed you arn't closing the connection to each database after you query from it. you should assign a variable to mysql_select_db and after you echo close the database like this:
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
while($row = mysql_fetch_array($result, MYSQL_BOTH)){
$dbName =$row['user_name'];
$db = mysql_select_db("dbprefix_".$dbName, $conn) or die("MySQL Error: " . mysql_error());
if( $db ){
// do a query for each db
$query = mysql_query('SELECT * FROM `products`');
$num_rows = mysql_num_rows($query);
echo $dbName." has".$num_rows."products"."<br/>";
mysql_close( $db );
}
}
also notice I took the mysql_connect() line out of the while loop because you don't need to call this more than once. and I added the $conn variable for your mysql_connect() command, this way you can use $conn in your mysql_select_db() statement. This tell the select_db statement which connection to look in for this database (just alittle more secure).
Seems that there is a typo here:
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
Did you mean "dbprefix_".$dbName instead of $bName?
You don't need to call
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
every time, just call mysql_select_db for each database and PHP will reuse the connection
This is a copy paste from php manual may be it helps you
If you use implode() with the return value by mysql_fetch_array,
if you use MYSQL_BOTH on parameter 2, the result is not really what you're expecting.
For example :
my sql database contains "Amine, Sarah, Mohamed";
$array = mysql_fetch_array($resource,MYSQL_BOTH);
or $array = mysql_fetch_array($resource);
echo implode(" - ", $array);
the result is : Amine-Amine-Sarah-Sarah-Mohamed-Mohamed
and we expect just : Amine-Sarah-Mohamed
You must use MYSQL_NUM or MYSQL_ASSOC on parameter 2 to resolve the problem.
Seems rather inefficient to start up a new connection, using the same user/password for every user you've got. MySQL is perfectly capable of querying across different databases from the same connection:
mysql_connect(...);
$sql = "SELECT user_name FROM userinfo";
$result = mysql_query($sql) or die(mysql_error()) {
while($row = mysql_fetch_assoc($result)) {
$username = $row['user_name'];
$sql2 = "SELECT count(*) AS cnt FROM dbprefix_{$username}.products";
$result2 = mysql_query($sql2) or (die(mysql_error());
echo "$username has {$result2['cnt']} products";
}
In short, doing
SELECT somedb.sometable.somefield
is the same as doing
mysql_select_db('somedb');
SELECT sometable.somefield;