I have a Table named "status" Which is used to store objects status. The table has 5 columns and except "symbol" column which it's type is VARCHAR utf8mb4_unicode_ci, All the others are just typical integers.
The problem is that because the symbol column can store English and Non-English characters, It returns NULL(With var_dump($row)) When I use my php file "getStatus.php" to retrieve the data from a row with Non-English symbol but It works well when I use English characters as symbol.
This is my table(the symbol on the second row is "تست"):
This is the php code, "getStatus.php" :
if(!isset($_GET["symbol"]))
die("please specify the symbol");
$con = mysqli_connect("localhost","root","******","****");
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `status` WHERE `symbol` = '" . $_GET["symbol"] . "';";
$result = mysqli_query($con,$query);
if (!$result)
die("unable to retreive status");
$row = mysqli_fetch_assoc($result);
if ($row["status"] == 1)
echo $row["percentage"];
else
echo -1;
I can successfully get data When I execute getStatus.php?symbol=EU which calls mysql with
SELECT * FROM `status` WHERE `symbol` = 'ER';
But When I execute getStatus.php?symbol=تست, I got null! The confusing point is that if I copy the query and enter it in mysql command line It will work but it doesn't work when I send the same query with mysqli in php!!
SELECT * FROM `status` WHERE `symbol` = 'تست';
Why it works in mysql commandline and phpmyadmin but not with mysqli?
Related
I'm still getting mysql error in my PHP script.
Problematic code:
$mquery = mysql_query("SELECT m.`id`, m.`name`, NULL AS `type`, NULL AS `code`, 0 AS `cat` FROM `menu` m UNION ALL SELECT l.`id`, l.`name`, l.`type`, l.`code`, l.`cat` FROM `lines` l UNION ALL SELECT s.`id`, s.`name`, s.`site`, s.`site`, s.`cat` FROM `sites` s ORDER BY `name` ASC");
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery)) { ... }
When i put this query into PhpMyAdmin - all is OK, i will get result. When I put this query into MySQL Workbench - all is OK, i will get result.
AND NOW: When I run script with parameter (http://domain/index.php?site=ABC) - ALL IS OK. When I run script without parameter (http://domain/index.php) - I get mysql error on this query: "Table 'test.menu' doesn't exist".
What "test.menu"?! Where is "test"? I don't want any "test", I have no "test" in my query. And why is it related on parameter in url? It's not dynamically generated query. Where is problem?
Sorry for my english
Solved, script structure:
$mydb = mysql_connect(...);
mysql_select_db(..., $mydb);
mysql_set_charset('utf8', $mydb);
function newMenu($db)
{
$mquery = mysql_query("...", $db);
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery) { ... }
}
myMenu($mydb);
But what i don't understand is: Why is it working without "$db" when parameter 'site' is in url?
Please check your mysql configuration in PHP. I am pretty sure you are using database name as 'test' because you've copied the code from somewhere. Change it to the actual name of your database and it will work.
The second parameter of mysql_query must be a connection variable.
<?php
$con = mysql_connect("localhost", "root", "mypass") or
die("Could not connect: " . mysql_error());
mysql_select_db("tutorials");
$result = mysql_query("select * from tutorials");
echo "<h2>Here is a list of the topics:</h2>";
while ($row = mysql_fetch_array($result)) {
echo $row['name']."<br />";
}
mysql_close($con);
?>
Could you give full php script? is the database config related to 'site' parameter ?
I am facing a problem with mysqli select queries.
The table I am using is called participant and has the following fields:
id int(11) AI PK
name varchar(255)
surname varchar(255)
birth varchar(32)
sex varchar(32)
email varchar(255)
telephone varchar(32)
club varchar(255)
startingGroup int(2)
This is a PHP file (called select.php):
$connection = mysqli_connect("localhost", "$user", "$pass", "$db_name");
$query = "SELECT id, name, surname FROM participant WHERE NOT 0";
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($connection, $query)) {
printf("Errormessage: %s\n", mysqli_error($connection));
}
$result = mysqli_query($connection, $query);
$arr = array();
if(mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
}
mysqli_close($connection);
echo $json_info = json_encode($arr);
which is later called by AngularJS in:
$http.post("select.php").success(function(data){
console.log(data);
$scope.newparticipants = jsonFilter(data);
console.log($scope.newparticipants);
});
The value returned by the first console.log is 'undefined' and by the second "". When I change my query to select only 'id' the whole thing works and data is visible. Any guess why it is so?
It occurred that in the database there were some diacritical marks coded in utf8_general_ci. I didn't have a clue on what's going on, because some queries responded correctly, some not. Selecting ids from particular range I was receiving a correct result. Selecting a range beside - I was getting undefined. I found it very hard to detect that the problem was with encoding(only some rows contained these diacritical marks).
If you are in a similar situation - check if your database has some non-standard encoding. If so define it in your code, just after opening a database connection, for example:
(procedural style)
mysqli_set_charset($connection,"utf8");
(object-oriented)
$mysqli->set_charset("utf8")
Thank you all for trying to resolve this problem.
This is not duplicated question, since I am asking how to use SET and INSERT in one PHP variable, there no any questions about AUTO_INCREMENT...
I have below page:
<?php
function genWO(){
$dbtype = "MySQL";
$username = "user";
$password = "pass";
$hostname = "10.10.10.10";
$dbname = "TABLES";
//connection to the database
$conn = new mysqli($hostname, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
if ($conn->query($insertNewWONum) === TRUE) {
echo "New record created successfully". "<br>";
} else {
echo "Error: " . $insertNewWONum . "<br>" . $conn->error;
}
$getWONum = "SELECT LPAD(max(WO_NUM) ,6,0) as NEW_WO_NUM from GENERIC_TABLES.WO_NUMBERS";
$result = $conn->query($getWONum);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "New WO Number: " . $row["NEW_WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
//close the connection
$conn->close();
}
?>
Since it is not allowed to use INSERT and SELECT for the same table in one query, I am trying to set variable and use it in INSERT query:
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
But it doesnt work, though it works fine if I am using this query in terminal.
Can anyone let me know how to achieve it please?
Since it is not allowed to use INSERT and SELECT for the same table in one query
All issues with your approach aside of course you can use INSERT and SELECT in one statement
INSERT INTO WO_NUMBERS (WO_NUM, WO_REQUESTOR)
SELECT COALESCE(MAX(WO_NUM), 0) + 1, 'Test'
FROM WO_NUMBERS;
Here is SQLFiddle demo.
Now what you need to realize is that your approach is unsafe for concurrent access. If this code is executed from two or more sessions simultaneously some or all of them may generate the same number effectively breaking your application.
Use AUTO_INCREMENT instead.
CREATE TABLE WO_NUMBERS
(
WO_NUM INT PRIMARY KEY AUTO_INCREMENT,
WO_REQUESTOR VARCHAR(32)
);
INSERT INTO WO_NUMBERS (WO_REQUESTOR) VALUES ('Test');
Here is SQLFiddle demo.
If for some reason you can't use AUTO_INCREMENT directly (and I honestly don't see why you couldn't) i.e. you need to add prefixes or augment the generated id/code in some way you can look this answer.
I am developing an appication on my WAMP now (PHP 5.5.12, MySQL 5.6.17).
I have a function that displays all the events on the page. As there is a column called city, but in the database this column contains cityID, I wrote a function that will query the database to get city name by id.
So, that's what I have:
$city = self::getCity($row['id']);
and my getCity():
// Getting Config file data (DB connection info);
$conf = $this->getConf();
$mysqli = $this->dbConnect($conf);
// Quering...
$query = "SELECT * FROM cities WHERE id = '" . $id . "';";
$result = $mysqli->query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
$row = $result->fetch_array();
$city = $row['city'];
return $city;
What I get here is: Invalid query: with no any error message. I assume my query is bad, but I tried to modify it in different ways (just to mention, I just tried this: DROP TABLE cities, cause there is just 3 or 4 entries).
But before I added the die($message) string, I was experiencing the Call to a member function fetch_array() on a non-object fatal error.
I must say that there is no any errors in dbConnect(), cause I call it from other functions and it works pretty well.
Where is my problem at? What am I doing wrong?
UPD: After switching the language of MySQL from French to English (it was set by default to French), and changing mysql_error to mysqli_error (my fault, sorry), it says me that No database selected.
TRY THIS
$query = "SELECT * FROM cities";
Where you wrote this
$query = "SELECT * FROM cities;";
see the ; inside the double quotes ??
I have database contain table named demnads
table contain 11 cell first one is id auto increasement
I want to add data's with this sql command in php :
<?php
$hostname_mystore = "localhost";
$database_mystore = "mystore";
$username_mystore = "root";
$password_mystore = "";
$mystore = mysql_pconnect($hostname_mystore, $username_mystore, $password_mystore) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_query("set character_set_server='utf8'");
mysql_query("set names 'utf8'");
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "INSERT into demands ( itemname , case , cname , fatora , client , cdate , ctime , prices , cmobile , numbers) values('$item[$i]','$cases[$i]','$customer[$i]','$fatora[$i]','$client[$i]','$dates[$i]','$times[$i]','$price[$i]','$mobile[$i]','$numbers[$i]' )";
?>
but data's didn't be inserted
You have switched from the mysql library (which is deprecated) to mysqli:
mysqli_connect_errno()
You should use one or the other.
Also, embedded array values need to be enclosed in curly brackets{$item[$i]}.
This assumes, of course, that these arrays and $i are defined elsewhere.
And you haven't shown the statement that actually inserts the data.
You forgot to call mysql_query( $sql, $conn )
Enclose your column names with backticks. case is a keyword within MySQL and as such can not be used as a column name without the backticks!
$sql= "INSERT into demands ( `itemname` , `case` , `cname` , `fatora` , `client` , `cdate` , `ctime` , `prices` , `cmobile` , `numbers`) values('$item[$i]','$cases[$i]','$customer[$i]','$fatora[$i]','$client[$i]','$dates[$i]','$times[$i]','$price[$i]','$mobile[$i]','$numbers[$i]' )";
You said your table name is demnads . But in Coding you used demands?
Check again.