Define constant PHP - php

I have a multi-language script that works like this:
en.php
define('lang_hello_world', 'Hello World!');
index.php
<?php include('en.php'); echo lang_hello_world; ?>
The script works fine and replace the language. But now I need to convert the constant that are stored on MySQL.
The lang_hello_world is in MySQL and I need to print converted on the page, how can I do this?

In the en.php, you need connect the database and define the value, something like this:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = mysqli->query("SELECT * FROM language_table WHERE language = 'EN' LIMIT 1");
$row = $result->fetch_assoc();
define('lang_hello_world', $row[0]['lang_hello_world']);
Hope can help!

Use constant(). If $row['var'] fetched from the database equals lang_hello_world then:
$val = constant($row['var']);
Now $val equals Hello World! if the English file is loaded. Or obviously:
echo constant($row['var']);

Just grab it out of your database before you put it in your constant?
<?php
mysql_connect("localhost", "root", "passw");
mysql_select_db("languages");
$query = mysql_query("SELECT lang_hello_world FROM languages");
$fetch = mysql_fetch_assoc($query);
define("lang_hello_world", $fetch['lang_hello_world']);
mysql_close();
?>

Related

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

php variable not saving output of query

I am very new to PHP and have been trying to find out where I am going wrong in the statement below:
if(empty($_POST['datepickere']))
{
$purchaseorderdate = mysql_query("SELECT purchaseorderDMY FROM purchaseorders WHERE Servicetag = '$_POST[stage]'");
}
else
{
$purchaseorderdate = "$_POST[datepickere]";
}
The else statement executes just fine however the if statement does not save the output of the query to "$purchaseorderdate"
Can someone please give me a pointer as to where I am going wrong? Sorry if there is syntax error or something like that.
datepickere = A field in my HTML form.
purchaseorderDMY = The field in the DB where the datepickere is saved
when a new content is added
Start by making a mysqli connection (this is right out the docs):
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Now update your code snippet with more exact copies from the documentation:
if (empty($_POST['datepickere'])) {
$myvar = mysqli_real_escape_string($link, $_POST['stage']);
$result = mysqli_query("SELECT purchaseorderDMY FROM purchaseorders WHERE Servicetag = '$myvar'");
$row = mysqli_fetch_assoc($result);
$purchaseorderdate = $row['purchaseorderDMY'];
} else {
// you don't need to quote a variable to use it
// but it must be quoted starting at PHP4 (a decade ago)
$purchaseorderdate = $_POST['datepickere'];
}

how do I check if mysqli connection is working?

I am really new on php and I am trying to create my own php shop cart. After some research I got myself stuck in the "function products" below because seems to me it is not working properly. I expect to see the names of my products on my mysql database but it is not showing anything. My user name is noivaemd_etalhes, I am using my correct password and my database name is noivaemd_cart and I created on this database the table called Products with my list of products available. Can anybody help me to figure out what am I doing wrong on the php instructions below???? I appreciate any help.
<?php
session_start();
$page = 'index.php';
function products() {
$con = mysqli_connect("localhost", "noivaemd_etalhes", "mypassword", "noivaemd_cart") or die (mysqli_error());
$res = mysqli_query($con, "SELECT id, name, description, price FROM Products WHERE quantity > 0 ORDER BY id DESC");
if (mysqli_num_rows($res)==0) {
echo "<font family=verdana><font size=6px><font color= #90882C><font style=normal><font variant= normal><br>No products available<br></font>";
}
else{
while($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
}
}
?>
This code:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
Should be:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$get_row ['name'].'</p>';
}
As your title ask also tell how to check if the mysqli database connection is successful you can use the below code:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Reference link: http://www.php.net/manual/en/function.mysqli-connect.php
It's not good practice to connect to your database directly in your code. Open another file, and save it has 'dbconnect.php' or whatever you choose to name it. Save it in the same root.
Inside DB connect, you connect to the database like this:
<?php
$mysql_host = "localhost";
$mysql_user = "username";
$mysql_pass = "";
$mysql_dbname = "Products";
$conn_error = "Sorry, Could Not Connect";
if(!#mysql_connect($mysql_host,$mysql_user,$mysql_pass)||!#mysql_select_db($mysql_dbname)){
die($conn_error);
}
?>
In your index.php, inside your php tags, write 'require "dbconnect.php";'.
Then you get your values like this:
$InfoQuery = " SELECT id, product, name FROM table_name WHERE quantity>0 ORDER BY id DESC";
$Info = mysql_query($InfoQuery);
while($InfoRow=mysql_fetch_assoc($Info)){echo "<p>".$InfoRow['id']."<br>". $InfoRow['product']"."<br>". $InfoRow['name']."</p>";}
Edit: What you did wrong is in your while loop, you fetched the table data from $res when it should be fetched from $get_row

MySQLi present still not connecting to database

I ran var_dump(function_exists('mysqli_connect')); and it returned boolean true.
I am running the following code
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
It did not do anything. It did not print anything on the result webpage.
When I use mysql functions instead then it works fine.
What do I need to do to use mysqli function?
Oop
<?php
$mysqli = new mysqli("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=$mysqli->query($showtablequery);
while($showtablerow = $mysqli->fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Even if you connected successfully, it cannot query the database without connection informatiokn.
Procedural
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($connect, $showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Instead of
$query_result=mysqli_query($showtablequery);
use
$query_result=$connect->query($showtablequery);
and instead of
$showtablerow = mysqli_fetch_array($query_result);
use
$showtablerow = $query_result->fetch_array();

Variable scope in PHP

I have an issue with php. The following code generates the error "PHP Warning: mysqli_close() expects parameter 1 to be mysqli, null given[...]" on the line containing the mysqli_query
<html>
<head>
<?php
$table = "prjsuggestions";
/$mysqli = NULL;
if(!empty($_POST['posttext'])){
$pnameempty = empty($_POST['postname']);
$ynameempty = empty($_POST['name']);
if($pnameempty || $ynameempty){
}
else{
$mysqli = new mysqli("localhost", "progclub", "", "progclub");
if(mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//successful query normally occurs here but code fails w/ or /wo it.
}
}
else{
printf("No information posted.");
}
?>
<title>Bucknell Programming Club</title>
</head>
<body>
<span id="posts">
<?php
$offset = 0;
$query = "SELECT * FROM {$table}";
$result = mysqli_query($mysqli, $query);
if($result !== FALSE){
//while(($post = mysqli_fetch_assoc($result)) !== NULL){
echo mysqli_num_rows($result);
$post = mysqli_fetch_assoc($result);
$author = $post['name'];
printf("Author: %s\n", $author);
echo "<br />";
printf("Post title: %s\n", $post['title']);
echo "<br />";
printf("%s\n", $post['text']);
echo "<hr />";
//}
}
else printf("oh nooo!");
mysqli_free_result($result);
mysqli_close($mysqli);
?>
</span>
</body>
</html>
Note that all queries have been checked out and are working correctly in phpmy, and that the original code contains an earlier query that adds data to the 'base, which also definitely works.
I have tried various combinations of static and global, and I have taken a thoroughish look at PHP's page on variable scope, alas I do not entirely understand it in this context (esp. given my inability to make my code work). Can somebody enlighten me as to the differing scopes here? I didn't think there should be any!!
Take a look at the documentation (specifically Example 1). There are a few example similar to yours.
The following should work, and it is similar to your code:
Note how the first argument of mysqli_query() is in fact your variable $mysqli. You were probably trying to put something else there.
Also, be sure to check your connection, like in the code below:
<html>
<head>
<?php
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
?>
</head>
<body>
<?php
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Use $mysqli */
if (mysqli_query($mysqli, "/* ... MySQL goes here... */") === TRUE) {
/* Success! */
}
mysqli_close($mysqli);
?>
</body>
</html>
OOOOOOOOOOoooooooooooooooooohh. D'oh. Yeah. Scope. Perhaps I should have though more about the fact that the variable is only initialized when data is written. Oops. Thanks guys.

Categories