This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 8 years ago.
I am trying to send query to mysql to insert some values into a table , this is not the first time I do this stuff and this is what making me getting crazy !
when I am printing the query it looks like this :
INSERT INTO hc_family_receive_relief
(hc_family_id,hc_received_kind,hc_received_date,hc_received_month,hc_received_year)
VALUES ('89','��� ��������','30','5','2014')
This is the first time I face this issue , what is the reason of it ?
I even try to save the PHP file as UTF-8 , UTF-8 with out BOM , Arabic characters still not inserted to the table ! .
the following is the function that I used to create the query dinamicly from $_POST array :
function add_family_recieve_relief($array)
{
if(empty($array))
return NULL;
$i = 0;
$titles = array();
$values = array();
$query = "INSERT INTO hc_family_receive_relief ";
foreach($array as $key => $value)
{
if($i == 0)
{
$titles[count($titles)] = "($key,";
$values[count($values)] = "('".$value."',";
}
if($i < count($array) - 1 && $i > 0)
{
$titles[count($titles)] = "$key,";
$values[count($values)] = "'".$value."',";
}
if($i == count($array) - 1)
{
$titles[count($titles)] = $key.") VALUES ";
$values[count($values)] = "'".$value."')";
}
$i++;
}
foreach($titles as $tvalue)
$query .= $tvalue;
foreach($values as $vvalue)
$query .= $vvalue;
echo $query;
$qresult = mysql_query($query);
if(!$qresult)
return False;
else return True;
}
and this is the page that recive $_POST and pass it to function add_family_recieve_relief:
<?
require_once('../db.php');
require_once('familyReliefAPI.php');
if($_POST['addfamilyrelief'])
{
if(empty($_POST['hc_family_id']) || !is_numeric($_POST['hc_family_id']))
die('<center><h4><font color="red">خطأ في المعالجة , الرقم المميز للعائلة غير موجود !</font></h4></center>');
$family_id = $_POST['hc_family_id'];
array_pop($_POST);
$addfrr = add_family_recieve_relief($_POST);
if(!$addfrr)
die('<center><h4><font color="red">مشكلة في الاضافة , الرجاء التأكد من المعلومات أو الاتصال</font></h4></center>');
else {
//print_r($_POST);
}
}
?>
also I make SET NAMES utf-8 query in the connection page to fix the character issues , but still not work ..
please HELP ME .. thanks
NOTE :
The query is getting true and insert all the values in table except the arabic field it leaves it empty !
Check the charset of the table which is present in the database
Related
I have a php code which insert questions and answers for a quiz into a mysql database and for each answer a specifically tinyint number. With this method I can choose which one is the correct answer by allocating the number 1 to it and 0 to the rest of them. What I want is to can allocate to the wrong answers the numbers 2, 3 and 4, not 0 to all. I hope you understood. My English is not so good. Thank you very much !
My code:
// Question query
$query = "INSERT INTO `questions`(question_number, text)
VALUES('$question_number', '$question_text')";
// Run query
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
// Validate insert
if ($insert_row) {
foreach ($choices as $choice => $choice_text) {
if($choice_text != '') {
if($correct_choice == $choice) {
$is_correct = 1;
} else{
$is_correct = 0;
}
Why don't you specify the wrong answer when it's not correct?
if($choice_text != '') {
if($correct_choice == $choice) {
$is_correct = 1;
} else{
$is_correct = $choice;
}
This question already has answers here:
How to flush output after each `echo` call?
(18 answers)
Closed 6 years ago.
I'm trying to do that in PHP.
This code should insert 500000 rows in users table and after each row should print the value of $C(last for loop counter) in new line but it doesn't work properly. It inserts rows correctly but it doesn't print $c after inserting the row.
Why doesn't it work like that?
And how can i update this code to work like i want?
Thanks all in advance
<?php
$handler = new PDO("mysql:host=localhost;dbname=test",'root','');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function randomname(){
$len = mt_rand(20,50);
$string = "";
for($i=0;$i<$len;$i++){
$ch = mt_rand(32, 122);
if(($ch == 32 && $string != "") || ($ch >=97 && $ch <=122))
$string .= chr($ch);
else
continue;
}
return $string;
}
function randomemail(){
$len = mt_rand(7,15);
$string = "";
for($i=0;$i<$len;$i++){
$ch = mt_rand(32, 122);
if(($ch == 32 && $string != "") || ($ch >=97 && $ch <=122))
$string .= chr($ch);
else
continue;
}
if($len < 10)
return $string."#hotmail.com";
else
return $string."#gmail.com";
}
ini_set('max_execution_time', 500000);
for($c = 0; $c<=500000;$c++){
$name = randomname();
$mail = randomemail();
$query = $handler->query("insert into users(name, mail, password, created_at) values('$name', '$mail', '123132', now())");
echo "$c</br>";
}
PHP will, for performance, write once everything is finished.
If you'd like to force to flush the output buffer, you can do it by wrapping the code that should be written out at once with this code:
ob_end_flush();
// You code goes here
ob_start();
Now, every time you write something (using echo, print or similar), PHP will flush their buffers and write the output. Note that this takes a toll on performance. There are also some webservers that tries to disable this, so some weaking might be necessary.
There is an error while i insert "3 + 1 room" or update description area with "3 + 1 room" in MySQL database.
I saw there is no addition sign "+" in MySQL log (data inserted in database)
UPDATE testtable set status='0',title='3 1 room',
description='3 1 Daire. 1 Balkon kapalı.' WHERE id='60';
create table testtable ( id int(11), status tinyint(4), title varchar(20),
description text) ENGINE=InnoDB DEFAULT CHARSET=utf8
php file
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
$val=$baglanti->exec("UPDATE testtable set status='0',title='$title',
description='$dest' WHERE ad_no='$ad_no' ");
return $val;
What should I do?
EDIT
update.php
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
$ID=Updt($table,$fields,$values,$alan,$fvalue);
if($ID!=0){
echo $ID;
}
?>
database.php
<?php
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag=$GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$val=$bag->exec("UPDATE $table set $sts WHERE $field='$fvalue'");
return $val;
}
?>
this one, programmers wrote code. I try to take question parts from all code. There were lots of codes in file.
My guess is that you are not generating the query you think you are.
This should allow you to see the query.
I have also added some error checking, that really should be used in this code.
I have amended the connection line as I am sure a newline in the middle of the $username variable will cause an error.
database.php
<?php
try {
$baglanti = new PDO("mysql:host=localhost;dbname=test;charset=utf8",
$username,$passwd);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag = $GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$sql = "UPDATE $table set $sts WHERE $field='$fvalue'";
echo $sql; // you can comment this line out when you are sure the SQL is good
$val = $bag->exec($sql);
return $val;
}
?>
update.php
Small amendment here just so you know whats actually being returned from the function is a count and not a row ID. It could also be FALSE, indicating an error occured in the Updt() function in the query.
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
//$ID=Updt($table,$fields,$values,$alan,$fvalue);
// this is not an ID it is a coumt of the number or rows
// updated by the Updt() function
$cnt = Updt($table,$fields,$values,$alan,$fvalue);
if ( $cnt === FALSE ) {
// then we had an error in Updt()
print_r($baglanti->errorInfo(), true);
exit;
}
if($cnt != 0){
echo 'Rows updated = ' . $cnt;
}
?>
I have to mention this as others will if I dont. Your code is open to SQL Injection you should really be using prepared statements. Maybe you should mention this to the Programmers you mentioned. Maybe you should also not assume everything they wrote was done correctly.
This question already exists:
Closed 10 years ago.
Possible Duplicate:
same roll number can not be added
I want my code to behave this way that if once i had added a roll number, it can not be added again in the registration..........same as if once an email adress is registered the error displays that EMAIL ADDRESS ALREADY BEEN TAKEN....
I am creating a function . of roll numbr value is 1 it shall display error and if not 1 it shall not display the error
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if{
$val = 1;
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
$obj_db->db_close();
}
}
?>
and the function is called at the page by this method
<?php
if(isset($_POST['btnSubmit']) and $_GET['action'] == "Add")
{
$val = $Tblstuden->selectroll($_POST['studentname'],$_POST['rollnumber']);
if ($val =='1')
{
$Tblstuden->copyPostData();
$Tblstuden->insert();
echo"asdf";
}
redirect("index.php?page=studentlist");
}
else
{
echo"abc";
}
?>
You probably want
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if ($row){
$val = 1;
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
}
?>
in line 8 of the top function - as otherwise the code won't compile.
Sub-note, your code is subject to mysql injection, you should look at using PDO (http://php.net/manual/en/book.pdo.php) for your database functions before you get used to the old method. Please. Do it now ;)
This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Closed 1 year ago.
I have some code that takes from a txt file a list of emails and inserts them into a database, making sure not to add the email if it's already in said database. What I'm trying to do now is filter emails as they are read from the txt file and NOT insert them if they are an exact or partial match to any strings within the $filter array. In other words, if the email has 'gmail', '.ru' or 'exec' anywhere within the email address, I don't want it added.
Any help to stop the bleeding from me pounding my head against a wall would be great!
The code:
$TheFile = "emails.txt";
$handle = fopen($TheFile, 'r');
$good_count = 0;
$bad_count = 0;
$filter= array("gmail",".ru","exec");
while (!feof($handle))
{
$Data = fgets($handle, 1024);
$output = explode (",",$Data);
$exist = mysql_query("SELECT * FROM table WHERE email='$output[0]'");
if (mysql_num_rows ($exist) == 0) {
$email = strtolower($output[0]);
$sql = "INSERT INTO table SET email='$email'";
mysql_query($sql);
$good_count = $good_count + 1;
}
else {
$bad_count = $bad_count + 1;
}
}
Use stripos in a validation function:
function validate_email($input, array $needles) {
foreach ($needles as $needle) {
if (stripos($input, $needle) === false) return false;
}
return true;
}
// ...
if (mysql_num_rows ($exist) == 0 &&
validate_email($output[0], $filter))
{
$email = strtolower($output[0]);
$sql = "INSERT INTO table SET email='$email'";
mysql_query($sql);
$good_count = $good_count + 1;
}
else {
$bad_count = $bad_count + 1;
}
Also, consider using a UNIQUE index in your table definition. This will cause a (catchable) MySQL error if the email already exists and will offload your script from doing a SELECT query for every email in your file.