Can't update/change field values in a database - mysql

theoretically I'll show you the code that works, I mean, it makes sense but I can not get no change in the table! : \
so, here is the code:
else if ($mode == 'password') {
$generated_password = substr(md5(rand(999,999999)), 0, 8);
change_password($user_data['user_id'],$generated_password);
update_user($user_data['user_id'], array('password_recover' => '1'));
email($email, 'Your new password', "Hi," . $user_data['nome'] . " \n\nYour new password is: " . $generated_password . "");
}
Functions:
function update_user($user_id,$update_data){
$update = array();
array_walk($update_data, 'array_sanitize');
foreach($update_data as $field => $data) {
$update[]='`' .$field. '`=\'' .$data . '\'';
}
mysql_query("UPDATE users SET " . implode(', ',$update) . "WHERE user_id = '$user_id'");
}
function change_password($user_id,$password) {
$user_id = (int) $user_id;
$password = md5($password);
mysql_query("UPDATE users SET password = '$password' WHERE user_id = $user_id");
}
I have not even written the email function because that works. Thanks in advance! :)

You should add some kind of error handling to your code. At least add or die('Error: '.mysql_error()) after each mysql_query() to at least get some idea of what went wrong when the queries are executed.
And if you just take code from somewhere and don't really understand what it does, don't be surprised, if it doesn't do what you want it to do.

Related

Unique Profile Slug with PHP and PDO

I am using a class to generate a string name profile to slug and next use an SQL command to tell me whats the unique value to use in insert command, the problem is the command isn't working properly, sometimes it is possible to return a value which already exist...
Thats the class I am using to generate the slug: (composer require channaveer/slug)
And this the example code:
use Channaveer\Slug\Slug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
This is the content of the table when the script run:
Do you know how can I improve the select command to prevent it to return existing slugs from DB?
Ok finally found a solution... Heres the code for who wants to generate unique profile slugs using PHP - PDO and MySQL
$string = "John Doe";
$string = mb_strtolower(preg_replace('/\s+/', '-', $string));
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$pdo = Conectar();
$sql = "
SELECT slug_perfil
FROM advogados_e_escritorios
WHERE slug_perfil
LIKE '$slug%'
";
$statement = $pdo->prepare($sql);
if($statement->execute())
{
$total_row = $statement->rowCount();
if($total_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = $row['slug_perfil'];
}
if(in_array($slug, $data))
{
$count = 0;
while( in_array( ($slug . '-' . ++$count ), $data) );
$slug = $slug . '-' . $count;
}
}
}
echo $slug;
//john-doe-1
You should check if the slug exists or not from your database. If it already exists then you can append some random string like the following
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as #YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
I have followed the same for my blog articles (StackCoder) too. Even LinkedIn follows the same fashion.
Following is screenshot from LinkedIn URL

Empty Fields in Database

Can someone explain me please why I am getting empty fields stored in database for title and article. I added if empty statement for title and article, but looks like something does not work.. empty fields are still stored in the database..
I also tried with if(isset($_POST['submit']) && !empty($_POST["submit"])) but without success..
Any suggestion??
if(isset($_POST['submit'])) {
$date_added = date("Y-m-d H:i:s");
$author = $_POST['author'];
if(empty($_POST['title'])) {
echo "title is required";
} else {
$title = $_POST['title'];
}
if(empty($_POST['article'])) {
echo "article is required";
} else {
$article = $_POST['article'];
}
$query = mysqli_query($con, "INSERT INTO posts (date_added, title, article, author) VALUES ('$date_added', '$title', '$article', '$author')");
if(!$query) {
die("QUERY FAILED" . " " . mysqli_error($con));
}
}
Thank you ..!
Using empty means it is set even though it is empty.
You need to try this:
if($_POST['article']=="" || $_POST['article']==null )

Codeigniter database retrieving both in uppercase, lowercase and mixed case

my code
// My code:
$this->db->select('*')
->from('tbl_login')
->where(['username'=>$this->input->post('username'),'password'=>$this->input->post('password')]);
$result = $this->db->get()->result();
if($result)
var_dump($result)
else
echo "not fount";
Doesn't matter what ever I input 'admin1' or 'ADMIN1' & 'password1' or 'PASSWORD1'
it retrieves data from the tables.
But what I actually want is data will be retrieve when case is matched correctly.
Could anyone help???...
Try this one
$query = $this->db->select("*")->from("tbl_login")->where("BINARY username= '".$this->input->post('username')."' and password = '".$this->input->post('password')."'");
$result = $this->db->get()->result();
if($result)
var_dump($result)
else
echo "not found";
Note: Basically use BINARY before your where conditions in Query.
Hope this will help!!

Select from table where table = id if session is lang_code

I'm trying to select the english menu title with if session and my current sql table "see code"
if($_SESSION['lang_code'] == 'en') {
echo $courseCat['course_cat_title'];
} else
echo $courseCat['course_cat_title'];
it prints so far good but only the dutch menu title, when I look in my DB I have this table that shows the language country id course_cat_lang_country, now I need to know how I can print the English title when page is www.yourdomain.nl/en/. the full code that I use now is this.
$QcourseCat = mysql_query("SELECT * FROM web_course_cat WHERE course_cat_id = 1");
$courseCat = mysql_fetch_assoc($QcourseCat);
echo "< h4>";
if($_SESSION['lang_code'] == 'en') {
echo $courseCat['course_cat_title'];
} else
echo $courseCat['course_cat_title'];
echo "< h4>";
How about this:
if($_SESSION['lang_code'] == 'en') {
$table='course_cat_eng';
}
else {
$table='course_cat_title';
}
$sql = "SELECT * FROM $table WHERE course_cat_id = 1";
if (! $resource = mysql_query($sql) ){
echo "Error reading from table $table";
}
else {
if (!mysql_num_rows($resource ) ){
echo "No records foin in $table";
}
else {
$courseCat = mysql_fetch_assoc($resource);
echo "<h4>";
echo $courseCat['course_cat_title'];
echo "</h4>";
//...
// other stuff you might want to do
}
}
Please comment if this is not what you are looking for, and I will revise my answer.
You aren't sorting your results to check the language country id. You are getting only the first row. You need to change the query to get the language that you want. Or loop through the results that you get checking which language they are.
In the code that you posted your if statement does the same thing in each branch. And you never use it to select data.
Also as per the comments use MYSQLi or PDO for your querys as MYSQL is deprecated.

Mysql dynamic sql statement with PDO and parameters

I want to create a dynamic sql statement and run it using PDO. My problem is that i have some parameters and i cannot think of a way to pass the parameters.
Ex :
$query = "Select * from tbl_task where 1=1";
if (!empty($name)) $query .= " AND name = ?";
if (!empty($status)) $query .= " AND status = ?"
$db_stmt = new PDOStatement();
$db_stmt = $this->db->prepare($query);
$db_stmt->bindParam (1,$name);
$db_stmt->bindParam (2,$status);
My parameters does not get binded and i don't know how many parameters i have to bind, unless i write the same if statements but with bindParam instructions.
I tryed with mysql_real_escape_string instead bindParam to PDO but for some reason my parameters are added empty.
Any idea on how can i build a dynamic query and bind parameters to PDO ?
Edit 1 :
$arr = array();
if (!empty($name)){
$query .= " AND `name` like :NAME";
$arr['NAME'] = $name;
}
$db_stmt = new PDOStatement();
$db_stmt = $this->db->prepare($query);
$db_stmt->execute($arr);
How can i write a "like" statement ? I tried
$query .= " AND `name` like :NAME" . "%";
and is not working.
What I usually do is the following:
$query = "Select * from `tbl_task` where 1=1";
$arr = array();
if (!empty($name))
{
$query .= " AND `name` = :NAME";
$arr['NAME'] = $name;
}
if (!empty($status))
{
$query .= " AND `status` = :STATUS";
$arr['STATUS'] = $status;
}
$this->db->beginTransaction();
try
{
$tmp = $this->db->prepare($query);
$tmp->execute($arr);
$this->db->commit();
}
catch(PDOException $ex)
{
$this->db->rollBack();
$this->log->error($ex->getMessage());
}
You can't add SQL code as a parameter; only data will do. You'll have to force these bits into $query. They won't be escaped then so they shouldn't contain user-submitted data.
What I usually do is the following:
$query = "Select * from tbl_task where 1=1";
if (!empty($name)) $query .= $db->parse(" AND name = ?s", $name);
if (!empty($status)) $query .= $db->parse(" AND status = ?s",$status);
$data = $this->db->getAll($query);
the idea is in having a function to parse placeholders in arbitrary query part instead of whole query.
I don't bother with native prepared statements though. They pollute PHP scripts with heaps of useless code with not a single benefit.
To answer updated question
as you've been told, you can't bind arbitrary query part. But a literal only.
So, make your literal looks like foo% and then bind it usual way.