Select from table where table = id if session is lang_code - mysql

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.

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 )

Can't update/change field values in a database

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.

MySQL SHOW TABLES from DATABASE except one

So ive got a fully working page to display a dropdown list of all tables avaliable in my database. however i want it to display the list of all tables except one (as one of the tables contains user information which i dont want shown...)
Is there a way to do this?
This is the section of the code ive got so far...
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
if (mysql_select_db($dbname, $conn))
{
?>
<form method="post" action="Browse.php">
<select name="tables">
<?php
while ($row = mysql_fetch_row($result)) {
?>
<?php
echo '<option value="'.$row[0].'">'.$row[0].'</option>';
}
?>
</select>
<input type="submit" value="Show">
</form>
<?php
//mysql_free_result($result);
if (isset($_POST) && isset($_POST['tables']))
{
$tbl=$_POST['tables'];
//echo $_POST['tables']."<br />";
$query="SELECT * from $tbl ORDER BY title ASC";
$res=mysql_query($query);
//echo $query;
if ($res)
{
?>
<table border="1">
<?php
while ( $row = mysql_fetch_array($res))
{
echo "<tr>";
//echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
//echo "<td>".$row[2]."</td>";
//echo "<td>".$row[3]."</td>";
echo "</tr>";
} ?>
</table>
<?php
}
}
}
Its no biggie if there isnt an easy way to do so as i've figured out that by doing the $query="SELECT * from $tbl ORDER BY title ASC"; it wont display the data (as there isnt a title column in the user details table)..but i dont want the table name to be shown in the dropdown box
Just a general query really...
Thanks
You can use a where clause with the SHOW TABLES statement.
The trick is knowing the name of the column that's generated by the SHOW TABLES statement as its name depends on your database name. The name of the column will be "tables_in_{your_dbname}". So if your database name is "blah" the column name will be "tables_in_blah".
So if the table you want to omit from your result set is called "secret_table" you can execute the statement like so:
SHOW TABLES WHERE tables_in_blah <> 'secret_table';
Or if you want to use a wildcard you can do it like so:
SHOW TABLES WHERE tables_in_blah NOT LIKE '%secret_table%';
Try this:
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'your_data_base_name'
AND table_name NOT LIKE '%USER_TABLE%';
Without like
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'your_data_base_name' AND table_name <> 'USER_TABLE';
Another alternative is to avoid outputting the table in question when you construct the list of options:
<?php
while ($row = mysql_fetch_row($result)) {
if ($row[0] != 'my_private_table_name') {
echo '<option value="'.$row[0].'">'.$row[0].'</option>';
}
}
?>

use a single return from a sql query

I'm using PHP to make a very specific sql query. For example sake, I have the user's ID number, but I need their name. So I do a sql query from that table with the ID number in order to return the name.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
Now I want to use that. What's the most succinct way to go about making that result into a variable ths I can use?
edit:
I'm hoping that this is not the answer:
$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $val){
$username = $val;
}
}
}
I have used something like this to keep it short in the past:
list($name) = mysql_fetch_row(mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db));
echo $name;
In my opinion, the best way to fetch any SQL result is through mysql_fetch_assoc(). To use it, you would do something like this:
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name']; // You get an array with each column returned from your query.
}
Still, MySQL extension has been replaced for MySQLi, which is acknowledged to be faster and more practical. It has both OOP and structural bindings, and takes more into account your server settings.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$name = mysql_fetch_row($result)[0];
You should use MySQLi as bellow:
$db = new MySQLi($host,$user,$pass,$db);
$query = $db->query('SELECT name FROM users WHERE userID='.$thisuserid);
$result = $query->fetch_object();
echo $result->name;
If you use SELECT * so you also can access via $result->{field_name}