PHP: Bir metin dosyası okuma ve MySQL, SQL ifadeleri yürütme

2 Cevap php

Ben, bir. Sql dosyasını yüklemek içeriğini okumak ve bir MySQL veritabanı karşı bu ifadeleri yürütecek PHP bir form oluşturmak istiyorum.

Şu anda fonksiyonunu get_file_contents kullanıyorum ama işe yaramıyor. Ben ne yapabilirim?

2 Cevap

Eğer dosya içinde birkaç sorguları varsa, gerekir ya:

I use this bit of Java code to import sql queries, it basically splits the file into lines using a specific regexp, and strip comment prefixes created by mysqldump. porting this to PHP should be pretty straight forward.

public static void importSQL(Connection conn, InputStream in) throws SQLException
{
    Scanner s = new Scanner(in);
    s.useDelimiter("(;\\s*(\r)?\n)|(--\n)");
    Statement st = null;
    int lineNum = 0;
    try
    {
        st = conn.createStatement();
        while (s.hasNext())
        {
            String line = s.next();
            if (line.startsWith("/*!") && line.endsWith("*/"))
            {
                int i = line.indexOf(' ');
                line = line.substring(i + 1, line.length() - " */".length());
            }

            if (line.trim().length() > 0)
            {
                try
                {
                    st.execute(line);
                }
                catch (SQLException e)
                {
                    logger.error("Error executing line #" + lineNum +  " : " + line , e);
                    throw e;
                }
            }

            lineNum++;
        }
    }
    finally
    {
        if (st != null) st.close();
    }
}

an alternative is to call mysql command line via system. something like :

<?php
system("mysql -u $user -p$password $dbname < $filename");
?>

ancak çeşitli nedenlerle (vs farkında olmalıdır performans, güvenlik etkileri) için üretim kodu için çok iyi bir fikir değildir.