Why only some mysqli queries work? - php

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.

Related

question mark show like "????" instead persian character from php or mysql...! [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 5 years ago.
excuse me...! my english is not very good!
until last week i'm use "www.000webhost.com" webhost and i had no problem!!!
But today I bought a new server and use old file like before...
I dont know the problem is from php files or database?
Please show me the solution
this my php code
<?php
//Creating a connection
$con = mysqli_connect("___","___","___","___");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*Get the id of the last visible item in the RecyclerView from the request and store it in a variable. For the first request id will be zero.*/
$id = $_GET["id"];
$sql= "Select * from db_app where id between ($id+1) and ($id+10)";
$result = mysqli_query($con ,$sql);
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
mysqli_free_result($result);
mysqli_close($con);
?>
this my database code
CREATE DATABASE `android_db`;
USE `android_db`;
CREATE TABLE IF NOT EXISTS `db_app` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`movie_name` varchar(45) NOT NULL,
`movie_image` varchar(10000) NOT NULL,
`movie_genre` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
);
This happens when the character set is not set.
Try after the mysql connection,
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
Taken from: http://php.net/manual/en/mysqli.set-charset.php

Delete one field based on a different field search results

I'm trying to delete an unnecessary link based on the results from a different field, i.e., if the "size" field is NULL (no attachment) then delete the folder link in another field. I've included a link to help make sense of my question along with the pitiful attempt I've made so far :-).
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'ticket_db');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());\
}
// Query for blank attachment link
$query = "DELETE FROM ('ticket_table') filepath WHERE (size is NULL)";
// Execute the query
$query = $dbLink->query($query);
}
Link to screenshot of database tables
Thank you,
Doug
You should not enclose a table name in quote ( but eventualli if the name contains spechia char or word you can use backticks)
"DELETE FROM ticket_table filepath WHERE size is NULL";
And don't use unuseful ()
or
"DELETE FROM `ticket_table` filepath WHERE `size` is NULL";

MySQLi: Non-English Characters

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?

Why is the server rejecting my PDO query?

I've been trying to write a simple search and display site with a drop down menu, I've tried using mysqli and PDO and I'm not getting the results. I've just checked the server log in cpanel and found that the access has been denied to the results page. The access must be all right for the drop down page as it is populating the drop down list. I can't see why it is being stopped. The server is running PHP 5.3.27 and MYSQL 5.5.36.
This is the drop down.
<form action="search3.php" method="post" >
<?php
$mysqli = new mysqli('localhost','user','password','engraved_stamps');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$query = "SELECT DISTINCT Country FROM engravers ORDER BY Country";
$result = $mysqli->query($query);
?>
<select >
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['Country']}\">";
echo $row['Country'];
echo "</option>";
}
$mysqli->close();
?>
</select>
<input type="submit" name="dropdown" />
</form>
This is the results page (action for restul) (called Search3.php)
<?php
$hostname = "localhost";
$user = "user";
$password = "password";
$connection = mysqli_connect($hostname, $user, $password,);
if(!$connection){
echo"Could not connect to server";
};
mysqli_select_db($connection,'engraved_stamps');
if(!mysqli_select_db($connection,'engraved_stamps')){
echo"could not connect to database";
};
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "none";
}
$sql= "SELECT * FROM engravers WHERE Country = :Country";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();
while ($row = $stmt->fetchObject()) {
echo $row->Country;
}
$mysqli->close();
?>
I think PDO and mysqli are different PHP extensions. You should choose only one thing to deal with your work.
e.g., you can use mysqli only, or PDO.
For more information about PDO, see: http://php.net/manual/en/pdo.construct.php
You are mixing two entirely different database extensions:
MySQL Improved Extension (aka mysqli):
$mysqli = new mysqli(...)
^^^^^^
PHP Data Objects (aka PDO):
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
^^^
Despite your question title and tags, your code seems to use mysqli entirely. You'll just need to get rid of the PDO bits.
You're also using some undefined variables:
$stmt = $pdo->prepare($sql);
^^^^
You're apparently not getting the corresponding error messages, which suggests you haven't configured your PHP development box to do so. As soon as you do it, you'll be possibly warned of some other issues.
Sorry abas_rafiq. the comments only allow a certain number of characters.
Here is the structure:
CREATE TABLE IF NOT EXISTS engravers (
Key int(10) NOT NULL AUTO_INCREMENT,
StampImages text NOT NULL,
Images text NOT NULL,
Country text NOT NULL,
Year int(4) NOT NULL,
Description text NOT NULL,
SGNumber text NOT NULL,
ScottNumber text NOT NULL,
Engraver1Surname text NOT NULL,
Engraver1OtherNames text NOT NULL,
Engraver2Surname text NOT NULL,
Engraver2OtherNames text NOT NULL,
Engraver3Surname text NOT NULL,
Engraver3OtherNames text NOT NULL,
Designer1Surname text NOT NULL,
Designer1OtherNames text NOT NULL,
Designer2Surname text NOT NULL,
Designer2OtherNames text NOT NULL,
Printer text NOT NULL,
Notes text NOT NULL,
PRIMARY KEY (Key),
UNIQUE KEY Key (Key)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=91 ;
They were not all "Not Null" when I set it up but I see they are now.
<?php
try {
//here add user and password and database please be sure u have used correct one
$dbh = new PDO("mysql:host=localhost;dbname=engraved_stamps",'root','');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
$STM = $dbh->prepare("SELECT * FROM engravers WHERE Country = :Country");
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "name";//here you can assing % too for value of any if u need tell me to recode, NOTE here now the value u have assign is (name) is the record value on ur engravers table for column of Country.
}
$STM->bindParam(':Country', $Country, PDO::PARAM_STR);
$STM->execute();
$row= $STM->fetchAll();
if(count($row)){
foreach($row as $data){
echo $data['Country'] . "<br />";// here country is the column of ur table u can echo other columns too
}
}else {
echo 'no row found';
}
?>

PHP SQL Temporary table won't work

I'm trying to understand how the temporary tables work. But even when I copy and paste it from my tutorials, I don't get the expected result.
See the code underneath for more info.
At the moment the .php file returns a blank page (no errors),
while i would expect it to be:
1 Row inserted.
I looked for the error code but found out that temporary tables don't have an error code.
Does someone know what I'm doing wrong?
<?php
$link = mysqli_connect("localhost","xxx","xxx","xxx");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity (Name CHAR(30)");
$city = "'s Hertogenbosch";
$city = mysqli_real_escape_string($link, $city);
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT INTO myCity (Name) VALUES ('$city')"))
{
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
mysqli_close($link);
?>
Looks like you have an error in your sql creation. You are missing a closing parenthesis: ")"
CREATE TEMPORARY TABLE myCity (Name CHAR(30)
Adrien.
this works for me
<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
$mysqli = new mysqli("localhost", "root", "admin123", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TEMPORARY TABLE CITIES (
id int(11) NOT NULL,
name varchar(64) NOT NULL
)");
//$mysqli->autocommit(FALSE);
$mysqli->query("INSERT INTO CITIES VALUES ('1', 'Bavaria')");
$mysqli->query("INSERT INTO CITIES VALUES ('2', 'Havana')");
//$mysqli->commit();
if ($result = $mysqli->query("SELECT * FROM CITIES LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
//$mysqli->query("DROP TABLE CITIES");
$mysqli->close();
Remember Temporary tables only exist by session, sometimes we need create conventional table and truncate later...
You would must think use DB lib like Doctrine DBAL or ADODb or something like that...

Categories