私信 关注
dt614037527
码龄6年
  • 0
    被访问量
  • 暂无
    原创文章
  • 暂无
    作者排名
  • 0
    粉丝数量
  • 于 2014-11-04 加入CSDN
获得成就
  • 获得0次点赞
  • 内容获得0次评论
  • 获得1次收藏
荣誉勋章
  • 最近
  • 文章
  • 资源
  • 问答
  • 课程
  • 帖子
  • 收藏
  • 关注/订阅

如何解决多个分配中的分配[] byte数据

How to fix this problem about datatype of this function.

Firstly, I'm new to Golang and am trying to learn it with some practice. I created a function to handle a request/GET http response.

func connect(url, token string) (data byte) {
    var bearer = "Bearer " + token
    res, err := http.Get(url)
    res.Header.Add("Authorization", bearer)
    defer res.Body.Close()
    data, _ := ioutil.ReadAll(res.Body)

    return data
}

The error warning.

cannot assign []byte to data (type byte) in multiple assignment

I just want the function to return raw data from API response

1回答
发布问题于 2 年前

将任何json数据放入带有$ .each的标记中

This is my PHP code:

Sessions::sessionStart();
$sql = 'select * from `products` where `id`=?;';
$result = $this->db->prepare($sql);
$result->bindvalue(1, $_SESSION['id']);
$result->execute();
header('Content-Type: application/json');
$data = $result->fetch(PDO::FETCH_OBJ);
$arr=array($data->name,$data->shorttozihat);
echo json_encode($arr);

And this is my AJAX code:

$.ajax({
  dataType: "json",
  url: 'EditPro/InputVal',
  success: function (data) {
    $.each(data, function (key, val) {
      $('p').append(val);
    })
  }
 });

I want every data from json to be stored in one p tag but it puts all json data in one P tag

0回答
发布问题于 3 年前

如何动态获取,更新,插入以使表的数量保持很小

I'd like to design a database. I have questions and I'll try to explain them the best way.

1) one has told me that if you don't want many details about the project or if you don't want to do many things by hand, go for dynamic idea which means that you don't have a table with columns, but you have a table which has columns as rows. is this a good approach? is it worth it?

2) if you have less tables, it's easier to scale. why is that?

3) Let's say I go for dynamic idea. so what I came up with is that I've created 3 tables. these 3 tables will always be the same and always be helpful for other tables that use dynamic idea. how? here is how.

form_types table

+----+------------+
| id | input_type |
+----+------------+
|  1 | select     |
|  2 | input      |
|  3 | bool       |
+----+------------+

dynamic_columns table

+----+---------------+--------------+
| id |     name      | form_type_id |
+----+---------------+--------------+
|  1 | year_of_issue |            1 |
+----+---------------+--------------+

type_values table

+----+-------------------+-------+
| id | dynamic_column_id | value |
+----+-------------------+-------+
|  1 |                 1 |  1996 |
|  2 |                 1 |  2005 |
|  3 |                 1 |  2008 |
+----+-------------------+-------+

now I can use these tables to add cars and fetch cars from database dynamically, but to make it work for cars, I'll use these 3 tables and also I had to add another 3 tables for cars.

cars

+----+
| id |
+----+
|  1 |
+----+

column_transport_type

+---------------+-------------------+
| dynamic_column_id | transport_type_id |
+---------------+-------------------+
|             1 |                 1 |
+---------------+-------------------+

car_columns_value

+----+--------+-------------------+-------+
| id | car_id | dynamic_column_id | value |
+----+--------+-------------------+-------+
|  1 |      1 |                 1 |  1996 |
+----+--------+-------------------+-------+

So let’s talk about the below 3 tables. From user, I get the transport_type_id that is written in column_tranport_type table. Let’s say I got transport_type_id as 1. with 1, I get that dynamic_column_id is equal to 1.. I go to dynamic_columns table and find all that has id equal to 1. so it’s year_of_issue. Then I check if year_of_issue is select or input and if it’s select, I also return select values with the column name “year_of_issue” to front-end so that after returning this information, I for-each loop that information and create the form dynamically. When he enters information into those columns that I dynamically fetched, I use car_columns_value table to put the values there. Do you understand my scenarion?

Is this the great way of how I should do this kind of things dynamically? My worries are that for each kind of things(car or ship) that I want it to work dynamically, I have to create 3 more tables. 3 tables are default and for every dynamic business logic(car,shop, ship) I need another 3 tables and another 3 tables and so on. As you know number of tables will grow and maybe that’s not dynamic so far. I was told that dynamic is good when you shorten the number of tables so that you can scale better. Just give me your ideas. Should I follow my approach or what should I do?

0回答
发布问题于 3 年前

现在重命名Laravel 5.4中的输入密码?

I have a project for Laravel which includes wordpress. They have a common database. When registering the user, the data is entered into the user table when I click forgot the password and enter the email. I receive a link with a token on which it is possible to reset the password, but when I enter the password an error is output that the password is not compatible. How can this be remedied?

That's what I have:

<form method="POST" action="{{ route('password.request') }}">
                {{ csrf_field() }}

                <input type="hidden" name="token" value="{{ $token }}">

                <div class="input-with-icon icon-left">
                    <span class="input-icon text-accent text-left">
                        <i class="fa fa-envelope" aria-hidden="true"></i>
                    </span>
                    <input id="email" type="email" name="user_email" value="{{ old('user_email') }}" required autofocus
                           placeholder="email">
                </div>
                @if ($errors->has('user_email'))
                    <span class="error-block">
                        <strong>{{ $errors->first('user_email') }}</strong>
                    </span>
                @endif
                <div class="spacer-20"></div>
                <div class="input-with-icon icon-left">
                    <span class="input-icon text-accent text-left">
                       <i class="fa fa-lock" aria-hidden="true"></i>
                    </span>
                    <input id="password" type="password" name="user_pass" required placeholder="Password">
                </div>
                @if ($errors->has('user_pass'))
                    <span class="error-block">
                        <strong>{{ $errors->first('user_pass') }}</strong>
                    </span>
                @endif
                <div class="spacer-20"></div>
                <div class="input-with-icon icon-left">
                    <span class="input-icon text-accent text-left">
                       <i class="fa fa-lock" aria-hidden="true"></i>
                    </span>
                    <input id="password-confirm" type="password" name="password_confirmation" required placeholder="Retype Password">
                </div>
                @if ($errors->has('password_confirmation'))
                    <span class="error-block">
                        <strong>{{ $errors->first('password_confirmation') }}</strong>
                    </span>
                @endif
                <div class="spacer-20"></div>
                <div>
                    <button type="submit" class="btn btn-nim btn-nim-clear" style="width: 100%">
                        reset password
                    </button>
                </div>
            </form>

Where do I change the password on user_pass?

1回答
发布问题于 4 年前

直接在浏览器中使用时收到的JSON数据,但不包含cURL

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://www.unocoin.com/trade?all');
$result = curl_exec($ch);
curl_close($ch);
$data = json_decode($result);
return $data;

JSON data is received when directly used in browser, but not with cURL in PHP.

1回答
发布问题于 4 年前

如何分阶段替换单词以获得所需的结果?

Brief

Hello. I just can not get the result I want. So I divided the problem into pieces to solve. If of course someone will decide. If in general this is possible. I have text and three arrays. It is necessary to replace in three stages to solve the problem.

Examples:

$array_for_step1 = array // Array for 1-st step
(
    "ewery day"     => "every day",
    "to school"       => "to univer",
);

$array_for_step2 = array // Array for 2-nd step
(
    'I',
    'go',
    'metro',
);

$array_for_step3 = array // Array for last 3-rd step
(
    "my"   => "he",
    "metro"  => "bus",
);

Input text:

$input = "Ewery day I go To SchooL with metro. My friend too go to school but without metro.";

Comments to the decision stages:

Step 1:

Here you need to replace the keys of the array with their values in the text. Input text form after 1-st step replace using array $array_for_step1:

Highlighted bold - changed words in the text.

Every day I go To UniveR with metro. My friend too go To UniveR but without metro.

Step 2:

Highlighted bold - words that do not need to be replaced in the next step

Here you need to find words from the array and mark them out from the text so that they are not replaced or not available for replacement for the third step. Input text form after 2-nd step replace using array `$array_for_step2`:

Every day I go To UniveR with metro. My friend too go To UniveR but without metro.

Step 3:

Here you need to replace the keys of the array with their values in the text. Input text form after 3-rd step replace using array $array_for_step3:

Highlighted bold - Allocated those words that are not given a change.

Every day I go To UniveR with metro. My friend too go To UniveR but without metro.

Final result:

"Every day I go To UniveR with metro. My friend too go To UniveR but without metro."

My example function for replace array keys to value an any string cases:

function ReplKeyToValue($request, $dictionary) // $request = string && $dictionary associative array
{
    $request = str_replace($search, $replace, $request); // replace special letters to default cyrillic letters

    $result = preg_replace_callback("/\pL+/u", function ($m) use ($dictionary) {
    $word = mb_strtolower($m[0]);
    if (isset($dictionary[$word])) {
        $repl = $dictionary[$word];
        // Check for some common ways of upper/lower case
        // 1. all lower case
        if ($word === $m[0]) return $repl;
        // 2. all upper case
        if (mb_strtoupper($word) === $m[0]) return mb_strtoupper($repl);
        // 3. Only first letters are upper case
        if (mb_convert_case($word,  MB_CASE_TITLE) === $m[0]) return mb_convert_case($repl,  MB_CASE_TITLE);
        // Otherwise: check each character whether it should be upper or lower case
        for ($i = 0, $len = mb_strlen($word); $i < $len; ++$i) {
            $mixed[] = mb_substr($word, $i, 1) === mb_substr($m[0], $i, 1) 
                ? mb_substr($repl, $i, 1)
                : mb_strtoupper(mb_substr($repl, $i, 1));
        }
        return implode("", $mixed);
    }
    return $m[0]; // Nothing changes
    }, $request);


    return $result;
}

I gave an example of the text and the value of the array in English. But this is so that you can decide and understand easily. But I need that your solution work for Cyrillic text and array.

1回答
发布问题于 4 年前

将类绑定到Container

Suppose I have the following class:

class MyClass {

    private $someVar;

    public function __construct($someParameter) {
        $this->someVar = $someParameter;
    }

    public function display(){
        return "This is the variable value " . $this->someVar;
    }

}

How am I suppose to bind this class to the container as I need to pass the variable to the constructor as well?

Normally, I would get an instance of the class and pass the variable. Like;

$param = 'this is my variable.';
$obj = new MyClass($param);
echo $obj->display();

I need to do this through the service provider.

0回答
发布问题于 4 年前

我靠运气解决的Golang僵局,需要说明

I'm trying to understand go channel and go routine. To do so, I'm doing online exercises. I found one here: http://whipperstacker.com/2015/10/05/3-trivial-concurrency-exercises-for-the-confused-newbie-gopher/

I resolved the 3rd one (named "Internet cafe"). But there's something I resolved by "luck", and it's bother me because I don't understand my issue and why my "hack" fixed it.

In my code below, I replace "enterChan <- next" by "go func() { enterChan <- next }()", and it solved my deadlock.

Can someone explain to me why it deadlock before, and why it works with this hack ? Is it a proper solution, or an ugly one ?

Don't hesitate to criticize my code, I'm searching to improve :)

Many thanks!

This is my code:

package main

import (
    "fmt"
    "math/rand"
    "strconv"
    "time"
)

const (
    maxNumberOfUser = 8
)

func useComputer(tourist string, leaverChan chan string) {
    seed := rand.NewSource(time.Now().UnixNano())
    random := rand.New(seed)
    fmt.Println(tourist, "is online")
    d := random.Intn(120-15) + 15
    time.Sleep(time.Duration(d) * time.Millisecond * 10)
    fmt.Println(tourist, "is done, having spent", d, "minutes online.")
    leaverChan <- tourist
}

func manageUsers(enterChan, leaverChan chan string, stopChan chan struct{}) {
    nbUsed := 0
    queue := make([]string, 0)
    for {
        select {
        case tourist := <-enterChan:
            if nbUsed < maxNumberOfUser {
                nbUsed++
                go useComputer(tourist, leaverChan)
            } else {
                fmt.Println(tourist, "waiting for turn.")
                queue = append(queue, tourist)
            }
        case tourist := <-leaverChan:
            nbUsed--
            fmt.Println(tourist, "is leaving, number of free place is now:", maxNumberOfUser-nbUsed)
            if len(queue) > 0 {
                next := queue[0]
                queue = queue[1:]
                go func() {
                    enterChan <- next
                }()
            } else if nbUsed == 0 {
                close(stopChan)
                return
            }

        }
    }
}

func main() {
    enterChan := make(chan string)
    leaverChan := make(chan string)
    stopChan := make(chan struct{})
    go manageUsers(enterChan, leaverChan, stopChan)

    for i := 1; i <= 25; i++ {
        enterChan <- "Tourist " + strconv.Itoa(i)
    }
    <-stopChan
    fmt.Println("The place is empty, let's close up and go to the beach!")
}
0回答
发布问题于 4 年前

Codeigniter数据库连接错误和db_select

I'll try to be brief and to the point.

  1. I'm using Codeigniter 3.1.4. with HMVC
  2. Working perfectly on localhost with 'pconnect' = FALSE;
  3. Problem at live server through shared hosting.
  4. max_user_connections = 10. Set by the Hosting company.
  5. Also added mysql.allow_persistent = Off to php.ini file.
  6. Gives the error Message: mysqli::real_connect(): (42000/1203): User <user> already has more than 'max_user_connections' active connections Filename:mysqli/mysqli_driver.php Line Number: 201
  7. Line 201 is calling mysqli::real_connect within db_connect function of mysqli_driver
  8. CI's official statement is "...CodeIgniter intelligently takes care of closing your database connections".

With pconnect = FALSE; and CI's "intelligent" closing of database connections, I don't see what should be causing the problem.

EDIT

  • Was previously loading database groups through $this->load->database('group', TRUE); in each model (only one such call per model).
  • Tried resolving above error through autoloading 'database' library and setting $this->db->db_select('dbName'); in respective controllers+models but it's not always selecting the correct database when controller+model is loaded.
  • Does anyone know how db->db_select() works?

Any ideas would be great help. Thanks.

1回答
发布问题于 4 年前

是否可以使用php截断URL

I am trying to find a solution to truncating the URL instead of showing - http://mywebsite.com/main/android.php?dir=.%2Fandroid it should show: http://mywebsite.com/main/android/android.php

1回答
发布问题于 4 年前

处理SIGSEGV与恢复?

The signal package states:

Synchronous signals are signals triggered by errors in program execution: SIGBUS, SIGFPE, and SIGSEGV. These are only considered synchronous when caused by program execution, not when sent using os.Process.Kill or the kill program or some similar mechanism. In general, except as discussed below, Go programs will convert a synchronous signal into a run-time panic.

However, it seems recover() is not catching this.

Program:

package main

import (
    "fmt"
    "unsafe"

    "log"
)

func seeAnotherDay() {
    defer func() {
        if p := recover(); p != nil {
            err := fmt.Errorf("recover panic: panic call")
            log.Println(err)
            return
        }
    }()
    panic("oops")
}

func notSoMuch() {
    defer func() {
        if p := recover(); p != nil {
            err := fmt.Errorf("recover panic: sigseg")
            log.Println(err)
            return
        }
    }()
    b := make([]byte, 1)
    log.Println("access some memory")
    foo := (*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(9999999999999999)))
    fmt.Print(*foo + 1)
}

func main() {
    seeAnotherDay()
    notSoMuch()
}

Output:

2017/04/04 12:13:16 recover panic: panic call
2017/04/04 12:13:16 access some memory
unexpected fault address 0xb01dfacedebac1e
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x1 addr=0xb01dfacedebac1e pc=0x108aa8a]

goroutine 1 [running]:
runtime.throw(0x10b5807, 0x5)
        /usr/local/go/src/runtime/panic.go:596 +0x95 fp=0xc420043ea8 sp=0xc420043e88
runtime.sigpanic()
        /usr/local/go/src/runtime/signal_unix.go:297 +0x28c fp=0xc420043ef8 sp=0xc420043ea8
main.notSoMuch()
        /Users/kbrandt/src/sigseg/main.go:32 +0xca fp=0xc420043f78 sp=0xc420043ef8
main.main()
        /Users/kbrandt/src/sigseg/main.go:37 +0x25 fp=0xc420043f88 sp=0xc420043f78
runtime.main()
        /usr/local/go/src/runtime/proc.go:185 +0x20a fp=0xc420043fe0 sp=0xc420043f88
runtime.goexit()
        /usr/local/go/src/runtime/asm_amd64.s:2197 +0x1 fp=0xc420043fe8 sp=0xc420043fe0
exit status 2

Is there any way I could handle SIGSEGV in a way localized to certain parts of the code?

2回答
发布问题于 4 年前

map [string]结构体中的结构体

I have a JSON file that looks like this:

{
  "jailbreaks": [
    {
      "jailbroken": false,
      "name": "",
      "version": "",
      "url": "",
      "anleitung": [],
      "ios": {
        "start": "10.2.1"
      },
      "caveats": "",
      "platforms": []
    },
    {
      "jailbroken": true,
      "name": "Yalu102",
      "version": "beta 6",
      "url": "https://domain-dl.tld",
      "anleitung": [
        { "blog": "title", "link": "http://domain.tld/" },
        { "blog": "Test", "link": "http://google.at" }
      ],
      "ios": {
        "start": "10.2"
      },
      "caveats": "some text here",
      "platforms": [
        "Windows",
        "OS X",
        "Linux"
      ]
    },

And I create the object to work with like this:

type Jailbreak struct {
    Jailbroken bool   `json:"jailbroken"`
    Name       string `json:"name"`
    Version    string `json:"version"`
    URL        string `json:"url"`
    Anleitung  map[string]struct {
        Name string `json:"blog"`
        Link string `json:"link"`
    } `json:"anleitung"`

    Firmwares struct {
        Start string `json:"start"`
        End   string `json:"end"`
    } `json:"ios"`

    Platforms []string `json:"platforms"`
    Caveats   string   `json:"caveats"`
}

When I want to build my go program I get an error, that the JSON file cannot be read. But as soon as I delete the map[string]struct I can compile and run the program without any error and everything works fine. Am I messing around with something or is there an error in my JSON file?

2回答
发布问题于 4 年前

php表中断页面,下一页没有行

I am having a php table which contains information about billing of certain numbers. After generating this table I export it in pdf using mpdf. If the table has a certain number of rows it breaks the page in a weird way, leading the headers repeat on the next page with no rows. Here is the format of the table:

The table contains up to 3 headers inside <thead> tags, like this:

<table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse;" cellpadding="8">
    <thead>
        <tr>
            <td width="30.3%">Forbrug</td>
            <td width="23.1%">Periode</td>
            <td width="10.76%">Tid/MB</td>
            <td width="9.28%">Enheder</td>
            <td width="12.9%" align="right">I alt</td>
            <td width="13.3%" align="right">I alt+<b>moms</b></td>
        </tr>
    </thead>

rows are added in a while from the database in this way.. nothing special

<tr>
    <td>'.$produktNameFromDatabase.'</td>
    <td>'.$periodeFromDatabase.'</td>
    <td>'.$tidMbFromDatabase.'</td>
    <td>'.$enhederFromDatabase.'</td>
    <td align="right">'.number_format((float)$produktpris, 2, ',', '.').' kr.</td>
    <td align="right"><b>'.number_format((float)$produktpris*(1 + (0.25 * $moms)) - $momsDiscount, 2, ',', '.').' kr.</b></td>
</tr>

with the total lines at the end

        <tr>
            <td class="blanktotal" colspan="1" rowspan="6"></td>
            <td class="blanktotal" colspan="1" rowspan="6"></td>
            <td class="totals" colspan="2">Subtotal:</td>
            <td class="totals" colspan="2">'.number_format((float)$pris1, 2, ',', '.').' kr.</td>
        </tr>
        <tr>
            <td class="totals1" colspan="2">Moms:</td>
            <td class="totals1" colspan="2">'.number_format((float)$pris1*(0.25 * $moms) - $momsTotal, 2, ',', '.').' kr.</td>
        </tr>
        <tr>
            <td class="totals1" colspan="2"><b>TOTAL:</b></td>
            <td class="totals1" colspan="2"><b>'.number_format((float)$pris1*(1 + (0.25 * $moms)) - $momsTotal, 2, ',', '.').' kr.</b></td>
        </tr>
    </tbody>
</table>

!!! EVERYTHING that you have seen by now, including the totals are a part of the table!

Here is the mpdf settings that I have:

In PhP:

$mpdf=new mPDF('win-1252','A4','','',20,15,48,25,10,10);
$mpdf->useOnlyCoreFonts = true;    // false is default
$mpdf->SetProtection(array('print'));
$mpdf->SetTitle("Suggestive Title");
$mpdf->SetAuthor("Author");
$mpdf->SetWatermarkText("Faktura");
$mpdf->showWatermarkText = true;
$mpdf->watermark_font = 'DejaVuSansCondensed';
$mpdf->watermarkTextAlpha = 0.1;
$mpdf->SetDisplayMode('fullpage');

In HTML:

$html .= '<!--mpdf
    <htmlpageheader name="myheader">
        <table width="100%"><tr>
            <td width="50%" style="color:#000000;">
                <span style="font-weight: bold; font-size: 14pt;">
                    Company Name
                </span>
                Company Information
            </td>
            <td width="50%" style="text-align: right;">
                <img src="image.jpg" />
                    Invoice Information <br />Side: {PAGENO} af {nb}
                </td>
        </tr></table>
    </htmlpageheader>

    <htmlpagefooter name="myfooter">
        <div style="border-top: 1px solid #000000; font-size: 9pt; text-align: center; padding-top: 3mm; ">
            Footer Stuff
        </div>
        <div style="font-size: 9pt; text-align: center;">
            Other Footer Stuff
        </div>
    </htmlpagefooter>

    <sethtmlpageheader name="myheader" value="on" show-this-page="1" />
    <sethtmlpagefooter name="myfooter" value="on" />
mpdf-->';

Some styling that I use

body {font-family: sans-serif;
    font-size: 10pt;
}
p { margin: 0pt;
}
td { vertical-align: top; }
.items td {
    border-left: 0.1mm solid #000000;
    border-right: 0.1mm solid #000000;
}
table thead td { background-color: #d4ffaa;
    border: 0.1mm solid #000000;
}
.items td.blanktotal {
    background-color: #FFFFFF;
    border: 0mm none #000000;
    border-top: 0.1mm solid #000000;
    border-right: 0.0mm solid #000000;
}
.items td.totals {
    text-align: right;
    border-top: 0.1mm solid #000000;
    border-right: 0.0mm solid #000000;
    border-left: 0.0mm solid #000000;
}
.items td.totals1 {
    text-align: right;
    border-top: 0.0mm solid #000000;
    border-right: 0.0mm solid #000000;
    border-left: 0.0mm solid #000000;
}

The result looks something like this:

enter image description here

This issue occurs only when the number of rows fills the page. If it overflows it is no major issue, because the table headers are still there on the next page (all of them unfortunately, not only the last one) and the rest of the rows are added further.

How can I get rid of those empty rows, in this special case?

Thank you!

!!EDIT: Added more information, code and a better image of the case. Sorry for not doing it at the first time!

!!EDIT #2: I just observed on other examples that had more than 1 page of rows that the <thead>s keep their position on next pages. It happens all the time. Is there a way to disable that so that other <thead>s will just continue on the next page from the top of the page without remembering the position from the previous page?

2回答
发布问题于 4 年前

不能在Magento2中使用带有自定义表的getCollection

I'm trying to follow Alan Storm's tutorial here. The code works fine when I try to insert or retrieve a single record, but it cracks when I use collections. I followed all steps he illustrated in the tutorial, which drives me crazy because only collections wouldn't work!!

public function __construct(
\Magento\Backend\App\Action\Context $context,
\Vendor\Mymodule\Model\ConfigurationsFactory $myClass
) {
    $this->myClass = $myClass;
    parent::__construct($context);
}

public function execute() {
 $todo = $this->myClass->create();

 $collection = $todo->getCollection();

 foreach($collection as $item)
  {
    var_dump('Item ID: ' . $item->getConfigId());
    var_dump($item->getData());
  }
exit;

}

This gives the following error:

Vendor\Mymodule\Model\Configurations does not extend \Magento\Framework\DataObject

The code for configurations model is as below

namespace Vendor\Mymodule\Model;
use Magento\Framework\Model\AbstractModel;

class Configurations extends AbstractModel
{
    protected function _construct()
    {
        $this->_init('Vendor\Mymodule\Model\ResourceModel\Configurations');
    }
}

ResourceModel

namespace Vendor\Mymodule\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Configurations extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('vendor_configurations','config_id');
    }
}

Collection

namespace Vendor\Mymodule\Model\ResourceModel\Configurations;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    protected function _construct()
    {
        $this->_init('
             Vendor\Mymodule\Model\Configurations',
            'Vendor\Mymodule\Model\ResourceModel\Configurations');
    }
}

any hints would be really appreciated. Thanks

0回答
发布问题于 5 年前

symfony中的单元测试实体何时使用测试db?

I know that you can test your models by specifying a temporary test database to be used by your test framework. Is this something that should be used always when testing a model? Or testing the functionality of just the class without persisting anything to the database is ok?

1回答
发布问题于 5 年前

如何在php中插入另一个表后更新表

here is my php file... i want to update first table after successful insertion in second table,i am to select and insert properly but the row which i want to update is not getting updated after the data is inserted.

if($_SERVER['REQUEST_METHOD']=='POST')
    {
        $full_name=$_POST['full_name']; 
        $email_address=$_POST['email_address'];
        $contact_number=$_POST['contact_number'];
        $gender=$_POST['gender'];
        $location=$_POST['location'];
        $standard=$_POST['standard'];
        $institute=$_POST['institute'];
        $code=$_POST['code'];

        $sql = "SELECT * FROM activations WHERE code='$code' AND status='not used'";
        $check = mysqli_fetch_array(mysqli_query($conn,$sql));
        if(isset($check)==null)
            {
                echo  'exist';
            }
        else
            { 
                $sql1="INSERT INTO students(full_name, email_address, contact_number, gender, location, standard, institute)             VALUES('$full_name','$email_address','$contact_number','$gender','$location','$standard','$institute')";
            }
        if (mysqli_query($conn, $sql1)==true)
            {
                $sql2="UPDATE activations SET status='in use' WHERE code='$code';

    } else {
        echo "Error updating record: " . mysqli_error($conn);
    }    

can any one tell me how to write this in php mysqli procedural way.

1回答
发布问题于 5 年前

AJAX页面 - 如何使用#home等

I'm trying to make AJAX pages using the post from Tutorialzine.

This script makes pages appear using AJAX. The problem is that the script works with numbers, example: http://example.com/#page1, http://example.com/#page2 etc..

How to make this script so it doesn't need the #page1 or #page2 in the URL, but #home etc..

Sorry if I explained this wrong, English isn't my native language and it's hard for me to explain.

index.html

<script type="text/javascript" src="script.js"></script>
<ul id="navigation">
<li><a href="#page1">Page 1</a></li>
<li><a href="#page2">Page 2</a></li>
<li><a href="#page3">Page 3</a></li>
<li><a href="#page4">Page 4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>

<div id="pageContent"></div>

script.js

var default_content="";

$(document).ready(function(){

    checkURL();
    $('ul li a').click(function (e){

            checkURL(this.hash);

    });

    //filling in the default content
    default_content = $('#pageContent').html();


    setInterval("checkURL()",250);

});

var lasturl="";

function checkURL(hash)
{
    if(!hash) hash=window.location.hash;

    if(hash != lasturl)
    {
        lasturl=hash;

        // FIX - if we've used the history buttons to return to the homepage,
        // fill the pageContent with the default_content

        if(hash=="")
        $('#pageContent').html(default_content);

        else
        loadPage(hash);
    }
}


function loadPage(url)
{
    url=url.replace('#page','');

    $('#loading').css('visibility','visible');

    $.ajax({
        type: "POST",
        url: "load_page.php",
        data: 'page='+url,
        dataType: "html",
        success: function(msg){

            if(parseInt(msg)!=0)
            {
                $('#pageContent').html(msg);
                $('#loading').css('visibility','hidden');
            }
        }

    });

}

load_page.php

<?php

if(!$_POST['page']) die("0");

$page = (int)$_POST['page'];

if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');

else echo 'There is no such page!';
?>
1回答
发布问题于 6 年前

使用PHPExcel将xlsx转换为pdf并下载该pdf。 在localhost上工作正常

This code works fine on localhost but on live server it shows

File Not Found

Check the file name for capitalization or other typing errors. Check to see if the file was moved, renamed or deleted.

Here is my code

excel.php

<?php

error_reporting(1);
ini_set('display_errors', 0);
ini_set('display_startup_errors', TRUE);

$target = 'Myfile.xlsx';
include 'phpexcel/Classes/PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($target);

function datefix_excel($excel) {

    $dif=(41885-$excel)*86400;
    $seconds=1409737670-$dif;
    $date=date("d/m/Y",$seconds);
    return $date; }

//echo 'File ',pathinfo($inputFileName,PATHINFO_BASENAME),' has been identified as an ',$inputFileType,' file<br />';

//echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with the identified reader type<br />';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($target);

$i = 0;
$found = false;
try
{



    //
    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) 
    {

    //
    //$objWorksheet = $objPHPExcel->getActiveSheet();
    //now do whatever you want with the active sheet

    $worksheet->setShowGridLines(false);
    $worksheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER );
    $worksheet->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER );
    $worksheet->getPageSetup()->setFitToPage(true);
    $worksheet->getPageSetup()->setFitToWidth(1);
    $worksheet->getPageSetup()->setFitToHeight(0);

    $worksheet->getPageSetup()->setScale(40);
    $worksheet->getStyle('F1:F4')->getAlignment()->setWrapText(false);
    $worksheet->getStyle('D6:D8')->getAlignment()->setWrapText(false);


    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
    $count = 0;
    $found == false;

    //

$worksheetTitle     = $worksheet->getTitle();
$highestRow         = $worksheet->getHighestRow(); // e.g. 10
$highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
for ($row = 1; $row <= $highestRow; ++ $row) {
    for ($col = 0; $col < $highestColumnIndex; ++ $col) {
        $cell = $worksheet->getCellByColumnAndRow($col, $row);
        $val = $cell->getValue();

            if($val==$_REQUEST['roll'])
            {
                //echo "Roll Number found: ".$_REQUEST['roll']." <br/>";
                $found = true;
               // $objPHPExcel->getActiveSheet()->setCellValue('C23',$val);
               $objPHPExcel->getActiveSheet()->setCellValue('C23',datefix_excel($objPHPExcel->getActiveSheet()->getCell('C23')->getValue()));

                $rendererName = PHPExcel_Settings::PDF_RENDERER_DOMPDF;
                $rendererLibrary = 'dompdf';
                $rendererLibraryPath = './' . $rendererLibrary;
                //require_once (realpath(dirname(dirname(dirname(__FILE__))))."/libraries/pdf.php");
                //echo $rendererName.' and '.$rendererLibraryPath;
                if (!PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath)) {
                    die('NOTICE: Please set the $rendererName and $rendererLibraryPath values' .EOL .'at the top of this script as appropriate for your directory structure');
                }
                header("HTTP/1.1 200 OK");
                header("Pragma: public");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: private", false);
                header('Content-Type: application/pdf');
                header('Content-Disposition: attachment;filename="rename.pdf"'); //tell browser what's the file name
                header('Cache-Control: max-age=0'); //no cache
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
                $objWriter->setSheetIndex($i);
                //$objWriter->save('test.pdf');
                $objWriter->save('php://output');
                break;


            }
            else{
                continue;
            }


            }
        }

    //

}   
}
catch(Exception $e)
{
    //echo $e;
}


?>
1回答
发布问题于 6 年前

discuz模版Spacia 空间 【商业】GBK v1.1(jeavi_spacia)

2014 全新设计门户资讯模版,显示器宽屏时代的到来,各主流站点均调整宽度为1190px,因此本模板宽度也采用这个宽度,另外改模板论坛支持宽窄切换,美化设计界面包括,门户首页,资讯表页以及文章内页(您可以添加多个此类样式),论坛首页, 版块页,帖子内页,等等相关页面—— 模版经过为期一个多月的设计并测试,兼容目前各大主流浏览器,用户体验超赞,是款不错的模版风格!
rar
发布资源于 6 年前

将PHP数组存储到mySQL

I am trying to store some PHP arrays that come from a XML API servce into a MYSQL DB, and clear them on the session is closed or a new search is made

Have any ideea if this can be posible?

My Variables are $img[][], $name[] and $product[]->type[]->Category; and a unique variable:$searchID`

My final purpose is to store them into mySQL DB so i can create pagination system

Any advise will be much appreciated..

1回答
发布问题于 6 年前

php棘轮websocket javascript连接失败

I have telnet working but when I try the next part of the chat tutorial javascript fails to connect.

PHP code

 /* chat-server.php */
 use Ratchet\Server\IoServer;
 use Ratchet\Http\HttpServer;
 use Ratchet\WebSocket\WsServer;
 use MyApp\Chat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);

$server->run();





/* Chat.php */

namespace MyApp;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {

protected $clients;

public function __construct() {
    $this->clients = new \SplObjectStorage;
}

public function onOpen(ConnectionInterface $conn) {
    // Store the new connection to send messages to later
    $this->clients->attach($conn);

    echo "New connection! ({$conn->resourceId})
";
}

public function onMessage(ConnectionInterface $from, $msg) {
    $numRecv = count($this->clients) - 1;
    echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "
"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

    foreach ($this->clients as $client) {
        if ($from !== $client) {
            // The sender is not the receiver, send to each client connected
            $client->send($msg);
        }
    }
}

public function onClose(ConnectionInterface $conn) {
    // The connection is closed, remove it, as we can no longer send it messages
    $this->clients->detach($conn);

    echo "Connection {$conn->resourceId} has disconnected
";
}

public function onError(ConnectionInterface $conn, \Exception $e) {
    echo "An error has occurred: {$e->getMessage()}
";

    $conn->close();
}

}  

After I run on the command line php bin/chat-server.php which works fine next I run in the javascript console.

var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
    console.log("Connection established!");
};

conn.onmessage = function(e) {
    console.log(e.data);
};

But I get javascript error unable to connect.

UPDATE ERROR MESSAGE FROM GOOGLE CHROME

WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200
0回答
发布问题于 7 年前

如何在PHP中保护更多我的md5密码编码

I am seeking some suggestion to secure my password encoding. Here I wanted to mention that I don't want to use new password_hash() api and also dont want to migration of old password, If I used password_hash() api , I have to migrate my old user password, which is not gong to possible for now. SO here is my old approach.

function login() {
//the code of getting password from database.......I am skipping this part.....
if(!Check($given_pass,$expected_pass)))  
    //User enter a password in the session as given_pass and expected_pass is the md5 generated hash password stored in database.
    return error('pass error');
return notice('pass success');
}

function Encode($text) {
    return md5(paramtr2Str("conf.cryptographykey").$text);  
    //cryptography key is a random generated string at the server side.
}

function Check($given_pass, $expected_pass) {
    return $expected == Encode($given_pass);
}

I think my Encode function is hackable and I want to give it some extra security by sticking with the original formatting.

1回答
发布问题于 7 年前

Oracle绑定所有$ _POST

I am using oci_bind_by_name().

oci_bind_by_name($stid, ":post1", $_POST['post1']);
oci_bind_by_name($stid, ":post2", $_POST['post2']);
oci_bind_by_name($stid, ":post3", $_POST['post3']);
oci_bind_by_name($stid, ":post4", $_POST['post4']);
...

Is it possible to do this dynamically in PHP, for all $_POST keys call oci_bind_by_name() of the same name?

Just to simplify my code, as I have 50 or so calls to oci_bind_by_name().

2回答
发布问题于 7 年前

从模型中的if语句返回true或false,以便在视图中使用

Im using a MVC and I have the following function in my model:

public function subscribirUser(){
    $item_id = JRequest::getCmd('id');
    $user_id = JFactory::getUser()->id;

    //Coger todos los campos del cupon
    $db = $this->getDbo();
    $query = 'SELECT * FROM #__k2_items where id='.$item_id;
    $db->setQuery($query);

    $resultado = $db->loadObject();

    //Insertar el cupon como suscrito
    $query = 'INSERT INTO #__cuphoneo_subscripcion (user_id, item_id, fecha, estado) VALUES ('.$user_id.', '.$item_id.', now(), 1)';
    $result = $db->setQuery($query);
    $db->query();
    //Sacamos los valores de los campos extra
    $campos_extra = json_decode($resultado->extra_fields); 

    foreach($campos_extra as $value){ 
        if($value->id == 4){ 
            $num_max_cup_descargar = $value->value;
            $num_max_cup_descargar = $num_max_cup_descargar - 1;
            $value->value = $num_max_cup_descargar;
            $campos_extra_updated = json_encode($campos_extra);
            $query = 'UPDATE #__k2_items SET extra_fields=\''.mysql_real_escape_string($campos_extra_updated).'\' WHERE id='.$item_id;
            $db->setQuery($query);
            $db->query();
        }

        if($value->id == 8){ 
            $num_max_cup_desc_user = $value->value;

            $query = 'SELECT count(item_id) as contador FROM #__cuphoneo_subscripcion WHERE item_id='.$item_id.' AND estado=1';
            $db->setQuery($query);
            $resultado = $db->loadResult(); 

            if($resultado == $num_max_cup_desc_user){

            }
        }

        $fechaHoy = date("Y-m-d");

        //Comprobamos si la fecha de validez es igual a la fecha de hoy
        if($value->id == 12){
            if($value->value == $fechaHoy){
                $query = 'UPDATE #__k2_items SET publish_down=DATE_ADD("'.$fecha.'", INTERVAL 2 DAY) WHERE id='.$item_id;
                $db->setQuery($query);
                $db->query();
            }
        }

        //Comprobamos si la fecha de validez es igual a la fecha de hoy
        if($value->id == 23){
            if($value->value == $fechaHoy){
                $query = 'UPDATE #__k2_items SET publish_down=DATE_ADD("'.$fecha.'", INTERVAL 2 DAY) WHERE id='.$item_id;
                $db->setQuery($query);
                $db->query();
            }
        }
    }
}

I want to return true or false within each if so I can later use these to validate a button in my view. How can I do this?

1回答
发布问题于 7 年前

使用php将每个数组元素发送到数据库

I have an array like this

$a = scandir($dir)

It contains a list of folders in a directory. How can I store each element of the array as a new record in a database table? The only methods I have found so far convert the array to one long string.

I have tried

foreach($array as $item)
send each item to database 

But I receive the error " Notice: Undefined variable"

Full Code

$dir = "/some/folder";

// Sort in ascending order
$a = scandir($dir);

$string_version = implode(',', $a);

$array = explode(' ', $string_version);


foreach($array as $item)
{


$dbcon="INSERT INTO $DBTable(Column) VALUES('$item')";


}

?>
2回答
发布问题于 7 年前

获得无线电组的价值

I am developing a page for multiple choice questions. User is only able to select an answer for each question. I can't seem to retrieve the value (1 indicates correct answer) of the radio buttons.

Here is structure of two tables that I use

CREATE TABLE IF NOT EXISTS `question` (
`q_id` int(10) NOT NULL AUTO_INCREMENT,
`q_qstn_no` int(11) NOT NULL,
`q_text` varchar(300) NOT NULL,
`q_chpt` int(11) NOT NULL,
PRIMARY KEY (`q_id`)
)
CREATE TABLE IF NOT EXISTS `answer` (
`a_id` int(6) NOT NULL AUTO_INCREMENT,
`q_id` int(10) NOT NULL,
`a_text` varchar(255) NOT NULL,
`a_value` tinyint(1) NOT NULL,
PRIMARY KEY (`a_id`)
)

HTML form containing the radio group.

    <?php
    ini_set('display_errors',1);
    error_reporting(E_ALL ^ E_NOTICE);
    session_start();
    if(isset($_SESSION['tf1_sid']))
    {
    ?>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>
    <body>
    <form id="form1" name="form1" method="post" action="ques_page_calc1.php">
    <p>Questions</p>
    <table width="900" border="0" cellpadding="4">
    <?php
    // db connect
    include("dbconn.php");
    // db query for questions
    $sql_q  = "SELECT q_id, q_qstn_no, q_text FROM question";
    $query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
    // start loop for questions
    $rad2 = 0;
    while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){

    //        echo "<pre>";
    //        print_r($data_q);
    //        echo "</pre>";
    //        


        echo "<tr><td width='25' align='center' valign='top'><label><input name='q_no' size='1' type='hidden' value=". $data_q['q_qstn_no'] .">". $data_q['q_qstn_no'] ."</label></td>";
        echo "<td>". $data_q['q_text'] ."<br />";
        // db query for answers
        $sql_a = "SELECT a_id, a_text, a_value FROM answer WHERE q_id=".$data_q['q_id'];
        $query_a = mysql_query($sql_a) or die("MySQL Error: " . mysql_error());
        //$rad = 0;
        // start loop for answers
        while($data_a = mysql_fetch_array($query_a, MYSQL_ASSOC)){
            echo "<br /><table width='750' border='0'>";
            echo "<tr><td><label><input name='answer_".$rad2."' type='radio' value=". $data_a['a_value'] .">". $data_a['a_text'] . "</label></td></tr>";
            echo "</table>";
            //$rad++;
        }
        echo "</tr>";
        $rad2++;
    }
    echo "<tr><td><input name='Submit' type='submit' onClick='ques_page_calc1.php' value='Submit'></td></tr>";

    mysql_free_result($query_q);
    mysql_free_result($query_a);
    include("dbconn.php");

    ?>
    </table>
    </form>
    </body>
    </html>
    <?php
    }
    else
    {
    header("Location:s_login.php");
    }
    ?>

The PHP file to get the value selected

    <?php
    ini_set('display_errors',1);
    error_reporting(E_ALL ^ E_NOTICE);
    // include db connection file
    include("dbconn.php");
    session_start();

    if(isset($_POST['Submit']))
    {   
$id = $_SESSION['tf1_sid'];
echo $id;
$correct = 0;
$ev_id = 1;

//db query to obtain i_id
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_array($query_i, MYSQL_ASSOC);
print_r($data_i);

// capture values from HTML form
if(!empty($_POST['answer_'.$rad2]))
{   
    foreach(($_POST['answer_'.$rad2]) as $ans)
    {
    echo $ans;
    var_dump($_POST);

    if($ans == 1)
        $correct = $correct + 1;
    }

    //echo $correct;

    // insert answer to table
    //$sql_eval = "INSERT INTO eval_set (ev_id, q_id, response, created) VALUES ('" . $ev_id . "', '" . $ques_no . "', '" . $ans . "', CURDATE())";
    //mysql_query($sql_eval) or die ("Error: " . mysql_error());
    //}
    }
    //  
    // insert result to table
    //$sql_result = "INSERT INTO result (r_score, ev_id, s_id, i_id) VALUES ('" . $correct . "', '" . $ev_id . "',  '" . $id . "',  '" . $data_i . "')";
    //mysql_query($sql_result) or die ("Error: " . mysql_error());

    //echo "Result: " . $correct . " questions correct.";   

    //header("Location:ass_result.php"); 
    }

    // close db connection
    mysql_close($dbconn);
    ?>

I thought it was the $_POST['answer_'.$rad2] that was causing the problem since I wasn't sure how to concatenate variables to name field. But now that's changed, there is still no output beyond print_r($data_i); line in the PHP file.

2回答
发布问题于 8 年前

phpmyadmin localhost错误(xampp)

I am getting an error when I try to login to myphpadmin...

#1045 Cannot log in to the MySQL server
Connection for controluser as defined in your configuration failed.

is there something wrong with my config file?

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

/*
 * phpMyAdmin configuration storage settings.
 */

/* User used to manipulate with storage */
 $cfg['Servers'][$i]['controlhost'] = '';
 $cfg['Servers'][$i]['controluser'] = '<username here>';
 $cfg['Servers'][$i]['controlpass'] = '<password here>';

/* Storage database and tables */
// $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
// $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
// $cfg['Servers'][$i]['relation'] = 'pma_relation';
// $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
// $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
// $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
// $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
// $cfg['Servers'][$i]['history'] = 'pma_history';
// $cfg['Servers'][$i]['table_uiprefs'] = 'pma_table_uiprefs';
// $cfg['Servers'][$i]['tracking'] = 'pma_tracking';
// $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
// $cfg['Servers'][$i]['userconfig'] = 'pma_userconfig';
// $cfg['Servers'][$i]['recent'] = 'pma_recent';
/* Contrib / Swekey authentication */
// $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';

/*
 * End of servers configuration
 */

I couldnt help but notice that alot of this is committed out....should it be?

I really dont know what I am doing...any help would be amazing!!!!!

3回答
发布问题于 9 年前

修改smarty中的数组内容?

We are using smarty,

In one of our views we have:

{if $header.showNav}...{/if}

and if we want to set that we use:

$header = $smarty->getTemplateVars('header');
$header['showNav'] = true;
$smarty->assign('header', $header);

Which works, But it seems rather long winded.

Does smarty provide a way to manage this easier?

1回答
发布问题于 9 年前

有没有执行sql的函数? 具体是CakeSchema生成的sql?

Is there a function that executes mysql? Specifically mysql generated by the CakeSchema?

This is an example of the data I want to import:

    $this->Schema = new CakeSchema();
    $Schema = $this->Schema->load();
    $db = ConnectionManager::getDataSource($this->Schema->connection);
    $contents = "

" . $db->createSchema($Schema);
1回答
发布问题于 9 年前

从Wordpress自定义元框调用数据

Alright, I have created a custom meta box on the post edit screens for my custom post type. What I'd like to be able to do with it is allow the user to input a link and then have a button where the post is displayed to take the user to the specified link. What hook would I use to call the meta boxes data?

Thanks!

JWinton

1回答
发布问题于 9 年前

PHP SOAP服务 - 大于15MB的上传文件失败

Is there anything that would be preventing a PHP SOAP Service from uploading a file larger than about 15MB? Smaller files work great, but larger ones fail without any noticeable errors.

Settings that I might need to change? Nothing in the apache logs.

1回答
发布问题于 9 年前

特定MySQL日期查询情况的最佳实践

I need to implement a rather complex query based on several date options in Zend / MySQL and would be glad to get some advice from people who are not as stuck in my code as I am :)

I have a table "event_dates", with date descriptions that are tied to an event model in my app. Every event can have multiple event dates and those can have rather complex settings.

The things that are configurable and relevant to this question are the following:

  • Fix date
  • Date range (date_from, date_to)
  • Date range based on "on specific weekdays"
  • Date range based on "every n-th week" (every 2nd week, leaving one out every turn)
  • Date range based on "each n-th weekday in a month" (second monday)
  • and of course every combination of these.

I am trying to write down the queries before coding them, so I have a clear view on what is needed - but there are some combinations that I just can't figure out to process without pre-coding a list of possible dates.

How would you implement this - in theory, not asking for specific code here (yet :) ). Would you create a list of possible hits in PHP and then query them in an easier way, or would you rather do a complex query of twenty wheres and ands and so on?

Thanks for your time

  • Arne

PS: This might be helpful ->

CREATE TABLE `event_dates` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `events_id` int(11) NOT NULL,
  `datetime_from` datetime DEFAULT NULL,
  `datetime_to` datetime DEFAULT NULL,
  `date_from` date DEFAULT NULL,
  `date_to` date DEFAULT NULL,
  `time_from` time DEFAULT NULL,
  `time_to` time DEFAULT NULL,
  `date_type` tinyint(4) NOT NULL DEFAULT '0',
  `frequency_in_weeks` tinyint(4) DEFAULT NULL,
  `nth_wday_in_month_week` tinyint(4) DEFAULT '0',
  `nth_wday_in_month_wday` tinyint(4) NOT NULL DEFAULT '0',
  `is_mondays` tinyint(1) NOT NULL DEFAULT '0',
  `is_tuesdays` tinyint(1) NOT NULL DEFAULT '0',
  `is_wednesdays` tinyint(1) NOT NULL DEFAULT '0',
  `is_thursdays` tinyint(1) NOT NULL DEFAULT '0',
  `is_fridays` tinyint(1) NOT NULL DEFAULT '0',
  `is_saturdays` tinyint(1) NOT NULL DEFAULT '0',
  `is_sundays` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
2回答
发布问题于 10 年前

查询字符串中带#的值不会收到完整数据

I have one url with one code. http://www.example.com/exam.php?id=rteter#443545

Now when I click this URL, the value of the id is rteter, means it returns me only portion of code before #.

I have not sent the link with urlencode so please do not give that solutions. Links are already sent, is they any way by which I can get the full value in my php code?

Martha

3回答
发布问题于 10 年前